Problem in regular expression
I am trying to remove multiple spaces by using below codes,its removing   also, but its not working for character N B S P.....
replace(SPAC开发者_如何学运维E, " ").replace(/^[\s\t\n\ \;]+|[\s\t\n\ \;]+$/g, '');
Try:
str.replace(/( )|[ \t\n]/g, '')
Try /([ \r\n\t]| )/g
to remove all whitespace in the string,
Try /^([ \r\n\t]| )/g
to remove all whitespace from the beginning of the string,
Try /([ \r\n\t]| )$/g
to remove all whitespace from the end of the string,
To replace leading and trailing white-space and
you can do:
str.replace(/^( |\s)+|( |\s)+$/gi, '')
The reason by n
b
s
p
and ;
are being deleted from your string is because of the incorrect character class:
[\s\t\n\ \;]
which also matches characters n
b
s
p
and ;
.
Also note that \s
includes \t
and \n
.
In case if you want to delete all whitespace characters and all
from the string you can do:
str.replace(/( |\s)+/gi, '')
Could be less complex imho:
(' replace -s and spaces   in this line ok? ')
.replace(/ |\s|\s+/gi, '');
//=>result: 'replace-sandspacesinthislineok?'
With this RegExp/replace all instances of spaces/ -s are replaced with an empty string.
/ |\s|\s+/gi
-------^ or operator, so: match OR \s OR \s+
---------------^g modifier: match all instances in the string to search
-----------------^i modifier: match case insensitive
An even shorter form would be:
/( |\s)+/gi
----------------^ + match the preceding element one or more times
Wikipedia is your friend
精彩评论