正则表达式删除重复的空格,只留下 1 或 2 次出现

Regexp remove duplicate whitespace leaving only 1 or 2 occurences

我正在制作一个简单的评论框,我想通过仅用 1 或 2 个标记替换白色space 来删除多余的白色space,无论它们是换行符还是 spaces.

(\s){2,} 是我目前所拥有的。 但是,我想让用户能够加倍 space 他们的评论,并将其替换为 ,第一个捕获组,会将他们的行减少到单个 space。

基本上,

如果我有 1 个 space 或换行符, 然后将其替换为 1 space 或换行符。

如果我有 多于 1 space 或换行符, 然后将其替换为 exactly 2 spaces 或换行符。

谢谢。

text=document.getElemntById('comment_text_input').value
while(text.indexOf('\n\n\n')!=-1||text.indexOf('   ')!=-1) {
 text=text.replaceAll('\n\n\n','\n\n') //it makes '\n\n\n\n\n\n' to '\n\n\n\n', the next round '\n\n\n' and finally '\n\n'
 text=text.replaceAll('   ','  ') // the same with the newlines
  }
document.getElemntById('comment_text_input').value=text

您可以使用

.replace(/(\s{2})\s+/g, '')

详情:

  • (\s{2}) - 第 1 组:两个空白字符
  • \s+ - 一个或多个空格。

查看 JavaScript 演示:

const text = 'Abc 123\n DEF 234\n      New line'
console.log(text.replace(/(\s{2})\s+/g, ''));

您可以替换

的匹配项
(?<=\s)\s+/

与 space.

Demo

正则表达式为“匹配一个或多个前面有白色space 字符的白色space 字符”。 (?<=\s) 正面回顾

请注意,下面标记为 '^' 的字符由正则表达式匹配,然后替换为单个 space:

Two spaces  then three   then four    then five\n    then none
           ^           ^^          ^^^           ^^^^

当匹配项被替换为 space 时,字符串将变为以下内容。

Two spaces  then three  then four  then five\n then none

请注意,换行符后面的 space 是匹配的四个白色 space 字符中的第一个。