An alternative to the JavaScript trim() method?

nick asked this question 5 months ago
nick on Mar 13

Is there an alternative to the trim() method in JavaScript that removes any leading or trailing spaces in a string?

The method should remove the spaces from the beginning/end of the string and then return the new string.

2 suggested answers
rusty1_rusty1 on Apr 9 · Edited

You can use a regular expression with a replace() string method:

string.replace(/^\s+|\s+$/g, "")

This will take any leading and/or trailing spaces that may exist and removes them.

All browsers will support this.

0 replies
coderguy on Apr 9

This regular expression will do the trick for you:

string.replace(/^[ ]+|[ ]+$/g, '');

It will remove any leading/trailing spaces from your string.

Here's how you'd use it:

let string = "   My example string.   "
string = string.replace(/^[ ]+|[ ]+$/g, '');

// "My example string."
0 replies