How to Trim String in Javascript

    Nov 10, 2019       by Pankaj Kumar
javascript-trim-string-example.jpg

Javascript provides tons of inbuilt functions to work with data while working. Trim is also a javascript inbuild function that removes space from both ends of the string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

 

Javascript Trim String

This method returns the string trimmed/stripped of whitespaces from both ends of the string. It does not take any arguments. 

 

Syntax:

str.trim();

 

Example:

let str = "       Hello World!        ";
console.log(str.trim());  // Output:  "Hello World!"

 

New features with ECMAScript 10 (ES2019)

String.prototype.trimStart() and String.prototype.trimEnd()  added with ES10 to remove the leading and trailing whitespaces from the string. The functions trimStart() and trimEnd() are only available in ES2019, It means they will only work with modern browsers but not previous versions.

 

Javascript trimStart()/trimLeft

 trimStart() or trimLeft() remove the leading whitespaces from the string and does not affect the value of the string itself.

 

Syntax:

str.trimStart();

str.trimLeft();

 

Example:

let str = "       Hello World!        ";
console.log(str.trimStart());  // Output:  "Hello World!        "

console.log(str.trimLeft());  // Output:  "Hello World!        "

 

Javascript trimEnd()/trimRight()

trimEnd() or trimRight() method returns a new string with removed white space from the end of the original string.

Syntax:

str.trimEnd();

str.trimRight();

 

Example:

let str = "       Hello World!        ";
console.log(str.trimEnd());  // Output:  "       Hello World!"

console.log(str.trimRight());  // Output:  "       Hello World!"

 

Polyfill

Running the below code before any other code will create trim() if it's not natively available.

 

Example:

if (!String.prototype.trim) {

  String.prototype.trim = function () {

    return this.replace(/^[suFEFFxA0]+|[suFEFFxA0]+$/g, '');

  };

}

 

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!


WHAT'S NEW

Find other similar Articles here: