Trimming whitespace from a string is an operation that we have to do sometimes.
In this article, we’ll look at how to trim whitespace from a string in JavaScript.
String.prototype.trim
A simple way to trim whitespace from a string is to use the trim
method available with JavaScript strings.
We just call it by writing:
console.log(' abc '.trim())
String.prototype.trimLeft
If we only need to trim whitespace from the start of the string, we can use the trimLeft
method.
For instance, we can write:
console.log(' abc '.trimLeft())
to trim whitespace from the beginning of the string.
String.prototype.trimRight
If we only need to trim whitespace from the end of the string, we can use the trimRight
method.
For instance, we can write:
console.log(' abc '.trimRight())
to trim whitespace from the end of the string.
Trim String with Regex Replace
We can search for whitespace with a regex and call replace
to replace all the whitespace with empty strings.
For instance, we can write:
console.log(' abc '.replace(/^\s+|\s+$/g, ''))
to trim whitespace from both the start and the end.
^\s+
is the pattern for searching for whitespace at the start of the string.
^
means the start of the string.
Likewise, \s+$
is the pattern for searching for whitespace at the end of the string.
And $
means the end of the string.
The g
flag means we search for all instances of whitespace in the string.
Then to trim only starting whitespace, we write:
console.log(' abc '.replace(/^\s+/, ''))
And to trim only trailing whitespace, we write:
console.log(' abc '.replace(`/\s+$/`, ''))
And to trim all kinds of whitespace, we write:
console.log(' abc '.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '))
This includes the newline character in addition to spaces since we have \n
in the regex.
Conclusion
We can trim whitespace from a string with built-in JavaScript methods or with regex replace.