Remove any spaces from the start and/or end of a string?

Answered
itsbambi asked this question 5 months ago
itsbambi on Mar 13

When dealing with strings in my JavaScript code, I need to make sure they don't have any unnecessary spaces at the start or end.

For example, this string:

"   A string example.   "

Should be converted into a new version with those leading and trailing spaces removed:

"A string example."

Is there an easy way to do this in JavaScript?

3 suggested answers
nick on Apr 9 · Edited

The trim() method will be the easiest way to remove your leading/trailing spaces:

string.trim()

Info on the browser support.

0 replies
timmy123 on Apr 9 · Edited

Here's a couple options you can use for removing the trailing/ending spaces from your strings.

Option 1:

trim() method built into JavaScript:

string.trim()

Supported by all browsers besides Internet Explorer.

Option 2:

You can also use a regular expression:

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

This could be used like this:

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

// "A string."

Supported by all browsers.

0 replies
suparman21 on Apr 9

You can apply a replace() method on your string with a regular expression:

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

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

Here's how you'd use it:

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

// "Your string."
0 replies
Answered