JavaScript String trim() Method

The trim function is an inherent feature in JavaScript designed for eliminating leading and trailing white spaces from a string. This method specifically targets and removes any blank spaces located at the beginning or end of the string. Since trim is a method associated with strings, it is called upon by creating an object of the String class to utilize this function. An object instance of the String class needs to be initiated to apply the trim method effectively.

Note: The trim method does not change the original string; it just removes the leading and trailing whitespace characters.

Syntax:

The syntax of the trim method is as follows:

Example

str.trim()

Description:

str: The str is a String class object that will contain the string to be trimmed.

trim: The trim function does not accept any arguments or parameters within its parentheses.

Return Value

The method str.trim eliminates leading and trailing white spaces from a string and then returns the modified string.

Examples of String trim

Presented below are instances demonstrating the utilization of the trim function for eliminating elements from it. Within these illustrations, you will be guided on the implementation of this particular JavaScript function. Let's delve into the examples:

Example 1: Trimming whitespace from the beginning

In this instance, we will provide a string that includes only white spaces at its start.

Example

Example

function func_trim() {  

    var str = "        Example tutorial website";

    var trimmedstr = str.trim();   

    console.log ("Original String: '" + str + "'");

    console.log ("Original Length: " + str.length);



    console.log("Trimmed String: '" + trimmedstr + "'");

    console.log("Trimmed Length: " + trimmedstr.length);

}   

func_trim();

Output:

Output

Original String: '        Example tutorial website'

Original Length: 35

Trimmed String: 'Example tutorial website'

Trimmed Length: 27

Explanation:

The code snippet above demonstrates a function that eliminates additional spaces from the beginning of a string by utilizing the trim method. It also incorporates the length function to display the length both before and after the trimming process, aiding users in recognizing the variance between the original and trimmed strings.

Example 2: Trimming whitespace from the end

In this instance, we will provide a string that consists of whitespace characters solely at the end.

Example

Example

function func_trim() {  

    var str = "Example tutorial website      ";

    var trimmedstr = str.trim();   

    console.log ("Original String: '" + str + "'");

    console.log ("Original Length: " + str.length);



    console.log("Trimmed String: '" + trimmedstr + "'");

    console.log("Trimmed Length: " + trimmedstr.length);

}   

func_trim();

Output:

Output

Original String: 'Example tutorial website      '

Original Length: 33

Trimmed String: 'Example tutorial website'

Trimmed Length: 27

Explanation:

The code snippet above demonstrates a function that eliminates redundant spaces from the end of a string by employing the trim method. The length method is leveraged to display the string's length prior to and post trimming, enabling users to observe the alterations in both the original and trimmed strings.

Example 3: Trimming whitespace from both ends

In this instance, we will provide a string that contains spaces at the beginning and end.

Example

Example

function func_trim() {   

    var str = "     Example tutorial website     ";    

    var trimmedstr = str.trim();   

    console.log ("Original String: '" + str + "'");

    console.log ("Original Length: " + str.length);



    console.log("Trimmed String: '" + trimmedstr + "'");

    console.log("Trimmed Length: " + trimmedstr.length);   

}   

func_trim();

Output:

Output

Original String: '     Example tutorial website     '

Original Length: 37

Trimmed String: 'Example tutorial website'

Trimmed Length: 27

Explanation:

The code snippet above demonstrates a function that eliminates additional spaces from the start and end of a string by employing the trim function. The length method is applied to determine the length of the string both before and after trimming, showcasing the variance between the original and trimmed strings.

Example 4: Trimming whitespace using trimLeft or trimStart

The trimLeft method, also known as trimStart, eliminates leading whitespace exclusively from the beginning of a string. Essentially, it focuses on removing any whitespace characters at the start of the string and providing the modified string without those leading spaces.

Syntax:

Example

str.trimLeft()

See the example below -

Example

Example

function func_trim() {  

    var str = "     Example tutorial website    ";     

    console.log("Original String Length:", str.length);

    var trimmedStr = str.trimStart();   

    console.log("Trimmed String Length (using trimStart):", trimmedStr.length);

    console.log("Trimmed String:", `"${trimmedStr}"`);

}   



func_trim();

Output:

Output

Original String Length: 36

Trimmed String Length (using trimStart): 31

Trimmed String: "Example tutorial website    "

Explanation:

Within the provided code snippet, the trimLeft method, also known as trimStart, is employed to eliminate leading spaces exclusively within the string. By utilizing the length method, the script determines the string's length to illustrate the variance post-trimming, subsequently displaying this outcome in the console.

Example 5: Trimming whitespace using trimRight or trimEnd

Conversely, the trimRight or trimEnd function eliminates whitespace exclusively from the right side of the string. Essentially, it specifically targets and eliminates any whitespace at the tail of the string, resulting in a string devoid of trailing whitespace characters.

Syntax:

Example

str.trimRight()

See the example below -

Example

Example

function func_trim() {  

    var str = "     Example tutorial website    ";     

    console.log ("Original String Length:", str.length);

    var trimmedStr = str.trimEnd(); 

    console.log("Trimmed String Length (using trimEnd):", trimmedStr.length);

    console.log("Trimmed String:", `"${trimmedStr}"`);

}   

func_trim();

Output:

Output

Original String Length: 36

Trimmed String Length (using trimEnd): 32

Trimmed String: "     Example tutorial website"

Explanation:

Within the provided code snippet, the trimRight or trimEnd function exclusively eliminates trailing spaces within the string. Utilizing the length method, the script determines the string's length both before and after the trimEnd operation, subsequently showcasing the trimmed string and its updated length within the console.

Uses of the String trim Method

The trim function is employed to eliminate additional spaces at the beginning and end of a string. Below are some typical scenarios where the trim function is applied:

1. Cleaning of user input and storing clean data

The function eliminates unnecessary spaces that users may input in form fields such as name, email, and others. Its purpose is to guarantee that only trimmed strings devoid of additional whitespaces are stored in databases or files.

Example

Example

let n = "   Jane Foster   ";

let cleanName = n.trim();  

console.log(cleanName);

Output:

Output

Jane Foster

2. Search for functionality

It reduces the search terms to prevent inaccurate search outcomes.

Example

Example

let word = "  Programming  ";

let key = word.trim();  

console.log(key);

Output:

Output

Programming

4. Form validation

It verifies if the provided string is devoid of content, taking into account all characters and not solely spaces.

Example

Example

let letter = "     ";

if (letter.trim() === "") {

  console.log("Blank Message");

}

Output:

Output

Blank Message

5. Comparison of strings

It aids in ensuring precise string comparisons by eliminating concealed whitespace characters.

Example

Example

let value = " passkey ";

if (value.trim() === "passkey") {

  console.log("Correct passkey");

}

Output:

Output

Correct passkey

Conclusion

JavaScript provides a convenient trim function that eliminates any additional whitespace at the beginning and end of a user-supplied string. This method proves to be quite beneficial when dealing with data storage, user input, or string comparisons. Excessive spaces within a string can lead to ambiguity, but by leveraging the trim method, we can ensure the string is tidy and more manageable for manipulation.

It's crucial to understand that the trim function does not modify the original string; instead, it generates and returns a new string that has been trimmed. Additionally, it solely trims spaces from the beginning and end of the string, not from within the string itself.

In summary, the trim function is a straightforward and valuable tool that aids in maintaining the cleanliness, precision, and readiness of your strings for use in your program, by eliminating any excess spaces provided by the user.

Frequently Asked Questions (FAQs)

  1. Could you explain the purpose of the trim function in JavaScript?

The trim function in JavaScript is an inherent method for strings, designed to eliminate any additional whitespace characters located at the beginning, end, or on both ends of the specified string. Its operation results in the creation of a fresh string, while leaving the original string unchanged.

  1. Can the trim function eliminate spaces within the middle section of a string?

No, the trim method does not remove spaces from the middle of a string; it only eliminates spaces at the beginning and end of the string.

Is trim universally supported by all web browsers?

The trim method is compatible with contemporary web browsers such as Firefox, Edge, Safari, and Chrome.

In cases where the string does not contain any spaces to be trimmed, what would happen?

If there are no spaces at the start or end of the string in some cases then the trim method just returns the original string.

  1. What is the distinction between trim, trimStart and trimEnd?
  • The trim removes the spaces from both sides of the string.
  • The trimStart removes the spaces from the start of the string only.
  • The trimEnd removes the spaces from the end of the string only.
  1. Can we use trim on numbers?

No, the trim method is not applicable to numbers since it specifically operates on strings. When attempting to use trim on a number in JavaScript, the number will be converted to a string beforehand.

Input Required

This code uses input(). Please provide values below: