removing space and retaining the new line?
i want to repla开发者_如何学编程ce all the spaces from a string , but i need to keep the new line character as it ?
choiceText=choiceText.replace(/\s/g,'');
india
aus //both are in differnt line
is giving as indaus
i want newline should retain and remove the s
\s
means any whitespace, including newlines and tabs. is a space. To remove just spaces:
choiceText=choiceText.replace(/ /g,''); // remove spaces
You could remove "any whitespace except newlines"; most regex flavours count \s
as [ \t\r\n]
, so we just take out the \n
and the \r
and you get:
choiceText=choiceText.replace(/[ \t]/g,''); // remove spaces and tabs
You can't use \s
(any whitespace) for this. Use a character set instead: [ \t\f\v]
The \s
regex pattern matches all whitespace chars. According to MDN, \s
is "equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
".
The easiest way to subtract a line feed, a newline, char from \s
is to use a reverse, \S
, shorthand character class, put it into a negated character class, [^\S]
and add \n
into it, that is, [^\S\n]
.
See a JavaScript demo:
console.log(
"india\naus \f\r\t\v\u00a0\u1680\u2000\u200a\u2028\u2029\u202f\u205f\u3000\ufeff."
.replace(/[^\S\n]+/g, ''))
精彩评论