从间隔单词中删除空格?
假设有以下字符串:
hello world, h e l l o! hi. I am happy to see you!
有没有办法删除间隔单词中的空格,像这样?:
hello world, hello! hi. I am happy to see you!
我试过了,[^ ]+(s)但捕获组匹配所有空格。谢谢你。
回答
一种正则表达式方法可能是:
var input = "hello world, h e l l o! hi. I am happy to see you!";
var output = input.replace(/(?<=bw)s+(?=wb)/g, "");
console.log(output);
这是正则表达式模式的解释,它针对位于两侧的两个独立单个单词字符之间的空白:
(?<=bw) assert that what precedes is a single character
s+ match one or more whitespace characters
(?=wb) assert that what follows is a single character