![](/img/trans.png)
[英]Is there a JavaScript regular expression to remove all whitespace except newline?
[英]How do I remove all whitespaces except those between words with Regular Expression in Javascript
var str=" hello world! , this is Cecy ";
var r1=/^\s|\s$/g;
console.log(str.match(r1));
console.log(str.replace(r1,''))
在这里,我期望的输出是“ hello world !,这是Cecy”,这意味着删除字符串开头和结尾的空格以及非单词字符之前和之后的空格。 我现在的输出是“ hello world !,这是Cecy”,我不知道谁在“,”之前和之后删除空格,同时在“ o”和“ w”之间(以及其他单词字符之间)保留空格)。
ps我觉得我可以在这里使用分组,但不知道是谁
您可以使用RegEx ^\\s|\\s$|(?<=\\B)\\s|\\s(?=\\B)
^\\s
处理开头的空格
\\s$
处理最后一个空格的情况
(?<=\\B)\\s
处理非单词char后的空格
\\s(?=\\B)
处理非单词char之前的空格
编辑: 正如ctwheels指出的那样, \\b
是一个零长度的断言,因此,您不需要任何前瞻性或前瞻性。
这是一个更短,更简单的版本: ^\\s|\\s$|\\B\\s|\\s\\B
var str = " hello world! , this is Cecy "; console.log(str.replace(/^\\s|\\s$|\\B\\s|\\s\\B/g, ''));
\B\s+|\s+\B
\\B
匹配\\b
不匹配的位置 \\s+
匹配一个或多个空格字符 const r = /\\B\\s+|\\s+\\B/g const s = ` hello world! , this is Cecy ` console.log(s.replace(r, ''))
(?!\b\s+\b)\s+
(?!\\b +\\b)
负前瞻,确保后面的内容不匹配
\\b
位置为单词边界 \\s+
匹配任何空白字符一次或多次 \\b
位置为单词边界 \\s+
匹配任何空白字符一次或多次 const r = /(?!\\b\\s+\\b)\\s+/g const s = ` hello world! , this is Cecy ` console.log(s.replace(r, ''))
您正在寻找的方法是trim() https://www.w3schools.com/Jsref/jsref_trim_string.asp
var str = " Hello World! ";
console.log(str.trim())
yuo可以使用以下命令
str.replace(/ /g,'')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.