捕获有图案的尾部/前导白香料是否存在?

时间:2019-04-15 11:11:27

标签: javascript regex

假设您要在文本正文中替换搜索到的字符串,然后替换并“突出显示”该字符串,即,将其包装在带有CSS类的<span>中:


const highlight = (str, ptn) => {
  if (ptn === '') return str
  str.replace(new RegExp(ptn, 'g'), `<span class="highligh">${ptn}</span>`)
}

如何修改此正则表达式模式以包含前导/训练空白(如果存在)?因为跨度将不关心它所包围的空格,并且模式ptn可能是单词的一部分...

example   str            ptn      res (as appears when render)
1         this is a str  is       thisisa str
2         this is a str  i        thisis a str
3         this is a str  t        this is a str
4         this is a str  his      thisis a str

例如,例如4的替换将捕获尾随的" "

2 个答案:

答案 0 :(得分:1)

不确定要弄清楚结果是什么,但这就是您想要的:

const highlight = (str, ptn) => {
  if (ptn === '') return str
  return str.replace(new RegExp('\\s+'+ptn+'|'+ptn+'\\s+', 'g'), `<span class="highligh">${ptn}</span>`)
}

var test = [
    'is',
    'i',
    't',
    'his',
];
test.map(function(a) {
console.log(highlight('this is a str', a));
});

答案 1 :(得分:0)

我将直接使用正则表达式来匹配前导/尾随空白。

var str = 'this is a str his';
var result = str.replace(/( )*his( )*/g, (p)=>`<span>${p}</span>`)
console.log(result);