问题
what function will turn
this contains spacesinto
this contains spacesusing javascript?
I've tried the following, using similar SO questions, but could not get this to work.
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
Edited the question to focus more on the javascript aspect. Is there a simple pure javascript way to accomplish this?
回答1:
You're close.
Remember that replace
replaces the found text with the second argument. So:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!
newString = string.replace(/\s+/g,' ').trim();
回答2:
string.replace(/\s+/g, ' ').trim()
回答3:
I figured out one way, but am curious if there is a better way...
string.replace(/\s+/g,' ').trim()
回答4:
Try this one, this will replace 2 or 2+ white space from string.
string.replace(/\s{2,}/g, '')
来源:https://stackoverflow.com/questions/16974664/remove-extra-spaces-in-string-javascript