gpt4 book ai didi

javascript - 如何在 Javascript 中使用正则表达式删除单词之间的所有空格

转载 作者:行者123 更新时间:2023-11-30 07:52:37 26 4
gpt4 key购买 nike

  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”之间的空格(以及其他单词字符之间的空格) ).

附注我觉得我可以在这里使用组,但不知道是谁

最佳答案

方法一

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

关于javascript - 如何在 Javascript 中使用正则表达式删除单词之间的所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49385915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com