带有特殊字符的 JavaScript 正则表达式

时间:2021-01-09 14:46:51

标签: javascript node.js regex replace

我有一个单词列表。

['incrediblé', 'incred!blé', '!ncrédiblé']

我有一个字符串列表。

[
'This is incrediblé! incrediblé2!',
'This is incred!blé! incred!blé2!',
'This is !ncrédiblé. !ncrédiblé2!']

我想屏蔽出现在字符串中的单词。它不应该贪婪。也就是说,不应该掩饰Underable2 中的Underable。

以下是我尝试过但未能正确定位单词的代码。

var words = ['incrediblé', 'incred!blé', '!ncrédiblé'];

var strings = [
  'This is incrediblé! incrediblé2!',
  'This is incred!blé! incred!blé2!',
  'This is !ncrédiblé. !ncrédiblé2!'
];

strings.forEach(string => {
  console.log('========================================');
  words.forEach(word => {
    const regex = new RegExp('\\b' + word + '\\b', 'gi');
    const masked = string.replace(regex, '*'.repeat(word.length));
    console.log(regex.test(string), '|', word, '|', masked);
  });
});

我想保持单词边界。我不打算匹配单词 !ncrédiblé 中的 !ncrédiblé2

0 个答案:

没有答案
相关问题