如何删除除 Javascript 中带有正则表达式的单词之间的所有空格

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!,this is Cecy",意思是去除字符串开头和结尾的空格,以及非单词字符前后的空格。 我现在的输出是"hello world! , this is Cecy",我不知道谁删除“,”前后的空格,同时保留"o"和"w"之间的空格(以及其他单词字符之间的空格) ).

p.s。我觉得我可以在这里使用组,但不知道是谁

您正在寻找的方法是trim() https://www.w3schools.com/Jsref/jsref_trim_string.asp

 var str = "       Hello World!       ";
console.log(str.trim())

您可以使用 RegEx ^\s|\s$|(?<=\B)\s|\s(?=\B)

  • ^\s处理space开头的情况

  • \s$ 处理最后一个 space 的情况

  • (?<=\B)\s 处理 non-word 之后 space 的情况 char

  • \s(?=\B) 处理 space 在 non-word 之前的情况 char

Demo.

EDIT : 正如 ctwheels 指出的那样,\b 是一个 zero-length 断言,因此您不需要任何回顾也向前看。

这是一个更短、更简单的版本: ^\s|\s$|\B\s|\s\B

var str = " hello world! , this is Cecy ";
console.log(str.replace(/^\s|\s$|\B\s|\s\B/g, ''));

你可以使用下面的命令

str.replace(/ /g,'')

方法一

See regex in use here

\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, ''))


方法二

See regex in use here.

(?!\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, ''))