An alternative to the JavaScript trim() method?

Answered
nick asked this question 1 year ago
nick on Mar 13, 2022

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, 2022 · 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, 2022

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
Answered