Answered
I need a function or method that takes a string and removes any double (or more) consecutive spaces in the string.
For example, a string like this:
" An example string with lots of spaces. "
Should be converted into a new version with the unnecessary strings removed:
"An example string with lots of spaces."
How can I do that in JavaScript?
You can use a regular expression:
.replace(/\s+/g, " ")
As an example, here's how you could put it to use:
let string = " An example string with lots of spaces. ";
string = string.replace(/\s+/g, " ");
// string = " An example string with lots of spaces. "
Notice that this replaces each instance of a double or more space and replaces it with a single space.
If you want to remove the leading and trailing space, you can add the trim()
method.
Try this regular expression:
myString.replace(/ {2,}/g, " ");
This will remove any multiple space instances and replace them with a single space:
string = string.replace(/ +(?= )/g, "");
That should do the trick for you :)