首页 > 解决方案 > 捕获图案周围的尾随/前导白色调(如果存在)?

问题描述

假设您想替换文本正文中搜索的字符串并替换并“突出显示”它,即将它包装在<span>一个 css 类中:


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 替换他的将捕获尾随" "

标签: javascriptregex

解决方案


不确定是否很好理解结果应该是什么,但这是您想要的:

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));
});


推荐阅读