Javascript 捕获图案周围的尾随/前导白点(如果存在)?
假设您希望替换正文中搜索到的字符串,并替换和“突出显示”它,即使用css类将其包装在Javascript 捕获图案周围的尾随/前导白点(如果存在)?,javascript,regex,Javascript,Regex,假设您希望替换正文中搜索到的字符串,并替换和“突出显示”它,即使用css类将其包装在中: 常量突出显示=(str,ptn)=>{ 如果(ptn=='')返回str str.replace(新的RegExp(ptn,'g'),`${ptn}`) } 如果存在前导/训练空格,如何修改此正则表达式模式以包含它?因为span不关心它周围的空白,而且模式ptn可能是单词的一部分 example str ptn res (as appears when render)
中:
常量突出显示=(str,ptn)=>{
如果(ptn=='')返回str
str.replace(新的RegExp(ptn,'g'),`${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,his的替换将捕获尾随的
“
我将直接使用正则表达式来匹配前导/尾随空格
var str='这是一个str-his';
var result=str.replace(/()*his()*/g,(p)=>`${p}`)
控制台日志(结果)代码>不确定结果应该是什么,但这是您想要的吗:
const highlight=(str,ptn)=>{
如果(ptn=='')返回str
返回str.replace(新的RegExp('\\s+'+ptn+'|'+ptn+'\\s+','g'),`${ptn}`)
}
var测试=[
"是",,
“我”,
"t",,
“他的”,
];
测试映射(函数(a){
log(突出显示('thisastr',a));
});代码>@anubhava这行不通。如果<代码> PTN</代码>在一个单词的中间,它会分解一个单词。我在posttrystr.replace(/s*his/g,(p)=>`${p}`)
中解决了这个问题,您将看到您的解决方案不包括捕获的空间。我做了两个小更改,``let re=\\s+${ptn}\\s+${ptn}124;${ptn}\\s+
``和str replace(new RegExp re,'g'),(p)=>