Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 捕获图案周围的尾随/前导白点(如果存在)?_Javascript_Regex - Fatal编程技术网

Javascript 捕获图案周围的尾随/前导白点(如果存在)?

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)

假设您希望替换正文中搜索到的字符串,并替换和“突出显示”它,即使用css类将其包装在
中:


常量突出显示=(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</代码>在一个单词的中间,它会分解一个单词。我在posttry
str.replace(/s*his/g,(p)=>`${p}`)
中解决了这个问题,您将看到您的解决方案不包括捕获的空间。我做了两个小更改,``let re=
\\s+${ptn}\\s+${ptn}124;${ptn}\\s+
``和
str replace(new RegExp re,'g'),(p)=>