替换句子中没有多余空格的单词?

时间:2019-03-09 13:52:39

标签: javascript regex

我有一句话:“ 我是只美丽的乌龟”,我希望能够从这样的句子中替换任意单词。问题是我不需要多余的空间。因此,sentence.replace(/ *\w+ */g, "")将不起作用,因为它将在句子的前面或后面添加一个空格,而sentence.replace(/\w+g, "")也将不起作用。

1 个答案:

答案 0 :(得分:2)

如果要删除特定的单词并消除多余的空格,请执行以下操作:

const removeWord = (s, w) =>
  s.replace(new RegExp(`^${w}\\s+|\\s+${w}\\b|$\\b{w}\\s+|\\b${w}\b`, 'g'), '');

const str = 'this is a beautiful turtle.';

console.log(removeWord(str, 'this'));
console.log(removeWord(str, 'is'));
console.log(removeWord(str, 'a'));
console.log(removeWord(str, 'beautiful'));
console.log(removeWord(str, 'turtle'));

正则表达式\s+beautiful将与单词beautiful匹配,包括单词前面的任意数量的空格。