Answered
In my JavaScript application, I am often dealing with strings that are either going to be saved to my database or retrieved from the database.
When dealing with those strings, I need to remove any unnecessary leading spaces from them.
For instance, this string:
" My string example."
Should be converted to a new string that doesn't have the leading spaces:
"My string example.
Is there a simple way to do that in JavaScript?
You can use the trimStart() JavaScript method:
string.trimStart()
That will remove all leading spaces from your string.
You have some easy options that are built into JavaScript:
trim()
: removes leading and trailing spaces from your string.trimStart()
: removes leading spaces from your string.trimEnd()
: removes trailing spaces from your string.This regular expression will remove any leading white space from your string:
string.replace(/^\s+/g, "");