JavaScript Trim: trimStart and trimEnd method ES10/2019

JavaScript , , , 0 Comments

In this article, we will talk about two JavaScript trim methods: trimStart() and trimEnd() those are intorduced in ES10/2019 and will understand it with the help of examples.

JavaScript trim methods are used to remove spaces from string and specially trimStart() method is used to remove spaces from the start of the string. For example:

#1 trimStart Example

var greeting = '   Hello buginit.com   ';
console.log(greeting);
// expected output: "   Hello buginit.com   ";
console.log(greeting.trimStart());
// expected output: "Hello buginit.com   ";

In the above example we have a variable called greeting that holds a string value that has spaces in start and the end. Then we used trimStart() to remove the spaces from the start of the string.

Do you know there is an alias of trimStart() is called trimLeft() that also works the same as trimStart(). For example:

#2 trimLeft Example

var greeting = '   Hello buginit.com   ';
console.log(greeting);
// expected output: "   Hello buginit.com   ";
console.log(greeting.trimLeft());
// expected output: "Hello buginit.com   ";

Syntax

str.trimStart();
str.trimLeft();

Return value of trimStart

It returns a new string with removed whitespace from its beginning (left end).

#3 One more example of trimStart

var str = '   foo  ';

console.log(str.length); // 8

str = str.trimStart();
console.log(str.length); // 5
console.log(str);        // 'foo  '

trimEnd Method

Javascript trimEnd method is used to remove spaces from the end of the string. For example:

#4 trimEnd Example

var greeting = '   Hello buginit.com   ';
console.log(greeting);
// expected output: "   Hello buginit.com   ";
console.log(greeting.trimEnd());
// expected output: "   Hello buginit.com";

In the above example we have a variable called greeting that holds a string value that has spaces in start and the end. Then we used trimEnd() to remove the spaces from the end of the string.

trimEnd() also has an alias is called trimRight() that also works the same as trimEnd(). For example:

#5 trimRight Example

var greeting = '   Hello buginit.com   ';
console.log(greeting);
// expected output: "   Hello buginit.com   ";
console.log(greeting.trimRight());
// expected output: "   Hello buginit.com";

Syntax

str.trimEnd();
str.trimRight();

Return value of trimEnd

It returns a new string with removed whitespace from its end (right end).

#5 One more Example of trimEnd

var str = '   foo  ';

console.log(str.length); // 8

str = str.trimEnd();
console.log(str.length); // 6
console.log(str);        // '   foo'

MDN

Support

Method
trimStart()66?61?53
trimEnd()66?61?53

That’s all, If I have missed anything else please let me know. Share it with love.

Spread the love

Leave a Reply

avatar
  Subscribe  
Notify of