AppDividend
Latest Code Tutorials

Javascript String Trim Example | String.prototype.trim() Tutorial

0

Javascript String Trim Example | String.prototype.trim() Tutorial is today’s leading topic. String trimming is one of the most common tasks in any programming language that programmers to deal with.  The trim() method removes whitespace from both sides of the string. Whitespace in this context is all of the whitespace characters, including space, tab, no-break space, etc., and all the line terminator characters, including LFCR, etc. The trim() method returns the string stripped of whitespaces from both ends of the string. The trim() does not affect the value of the String itself. The trim() function does not take any arguments.

Javascript String Trim Example Tutorial

The syntax for the function is the following.

str.trim()

The trim() does not affect the value of the string itself. JavaScript provides three functions for performing the various types of string trimming. The first, trimLeft() that will strip the characters from the beginning of the string. The second, trimRight() that will remove the characters from an end of the string. The final function is trim() that removes characters from both ends.

#trimLeft() method

Let us take the following code to understand the trimLeft() method.

// server.js

let string = "  AppDividend";
console.debug(string.trimLeft());

See the output.

Javascript String Trim Example

Here, we have given the spaces from the start of the string. Means, the left side of the string there is a space. Now in the output, the spaces will be removed. We can enhance trimLeft() function by specifying the list of characters to remove. The enhanced version is shown below.

String.prototype.trimLeft = function(charlist) {
  if (charlist === undefined)
    charlist = "\s";

  return this.replace(new RegExp("^[" + charlist + "]+"), "");
};

#trimRight() method

If the string’s right side is space, then it will remove it.

The enhanced trimRight() function also accepts the single parameter representing the characters, that needs to be trimmed. The new trimRight()  function is shown below.

String.prototype.trimRight = function(charlist) {
  if (charlist === undefined)
    charlist = "\s";

  return this.replace(new RegExp("[" + charlist + "]+$"), "");
};

The function is quite similar to a previous one. The main difference is the regular expression pattern. Instead of using a ^ character to denote the beginning of the string, we use a $ character, which represents the end of the string.

See the following example code of trimRight() method in the string.

// server.js

let string = "AppDividend       ";
console.debug(string.trimRight());

See the output.

trimRight() method

#trim() method

The last function is elementary, and it relies on the previous two methods that we have discussed earlier. The javascript trim() method trims both at the beginning and the end of the string. The trim() function is useful for removing extra spaces typed by the users. Often, the users aren’t even aware that they have typed extra spaces. This fact could also lead to the login problems if, for example, the user registered himself with the trailing whitespace.

String.prototype.trim = function(charlist) {
  return this.trimLeft(charlist).trimRight(charlist);
};

See the following example of String trim() method in Javascript.

// server.js

let string = "     AppDividend       ";
console.debug(string.trim());

In the output, the space from both sides is trimmed.

The trim from jQuery is convenient if you are already using that library.

jQuery.trim('  your string   ');

For browsers that do not support the string.trim(), e.g., Internet Explorer 8 or earlier, you can add your own trim() method to string object’s prototype by including a following script in the <HEAD> section of your page, or if you are old node version then you need to add that script file at the start of your project prior to any script that uses string.trim():

if (!String.prototype.trim) {
 String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,'');
 }
}

The key points of the above function are the RegExp object and the special ^ character. The RegExp creates the regular expression object that matches text with the given pattern. In regular expressions, the ^ character denotes a beginning of a string. Please note that an input character list is case-sensitive.

#Remove last four characters

String trimming is a common task that programmers deal with. Trimming functions remove the whitespace from a beginning and/or end of a string. See the following code to remove the last four characters.

// server.js
let orgString = "appdividend";
let modString = orgString.substr(0, orgString.length - 4);
console.log(modString);

See the following output.

Remove last four characters

The Javascript substr() function can be called on any string with two integer parameters, the second optional. If only one provided, it starts at that integer and moves to the end of the string, chopping off the start. If two parameters submitted, it begins at the first number and ends at the second, chopping off the beginning and end as it is able.

#Trim specific character from a string in Javascript

See the following code example.

// server.js
let x = '|k|r|unal||';
let y = x.replace(/^\|+|\|+$/g, '');
console.log('Before trimmed:', x);
console.log('After trimmed:', y);
^\|+   beginning of the string, pipe, one or more times
|      or
\|+$   pipe, one or more times, end of the string

See the following output.

Trim specific character from a string in Javascript

In the above code, we have used a String replace() method. We have replaced the beginning and end of the string’s character with null or empty character, and in the final output, it looks like it is trimmed.

Remember, in the above code, and we have the character from beginning and end, not in the middle, the middle targeted character remains as it is. You can see that in the above program code’s output.

You can also create an ad-hoc function for that like following.

// server.js
 function trimChar(string, charToRemove) {
    while(string.charAt(0)==charToRemove) {
        string = string.substring(1);
    }

    while(string.charAt(string.length-1)==charToRemove) {
        string = string.substring(0,string.length-1);
    }

    return string;
}

In the above code, we have used in-built String charAt() and substring() function.

#ES6 spread operator

Here is an approach I’d choose over the regex function using the ES6 spread operator. See the following code example.

function trimByChar(string, character) {
  const first = [...string].findIndex(char => char !== character);
  const last = [...string].reverse().findIndex(char => char !== character);
  return string.substring(first, string.length - last);
}

In the above function, the trimByChar() accepts the two parameters. A string and a character.

We have used the findIndex(), reverse(), and substring() function in the above code.

This implementation is good because the decision “tree” within regex engines is much bigger. In the above code, we have not used regexp, and sometimes, without regexp, the results are fast.

Finally, Javascript String Trim Example | String.prototype.trim() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.