正则使用场景

场景1:

{
    "location":"er",
    "page":"er",
    "title":"er",
    "alwaysSendReferrer":true,
    "clientId":"{{正则}}",
    "allowLinker":true,
    "legacyCookieDomain":"{{10086}}",
    "sampleRate":"{{1}}",
    "siteSpeedSampleRate":"{{1}}",
    "legacyHistoryImport":true,
    "allowAnchor":true,
    "cookieDomain":"{{正则}}",
    "storeGac":true,
    "cookieExpires":"{{正则}}",
    "name":"{{1}}",
    "cookieName":"{{10086}}",
    "trackingId":"{{1}}"
}

将以上字符串中所有{{}}的内容进行替换

{{正则}}替换成<span class='changeColor' onclick='showDialog("{{正则}}2")'>{{正则}}</span>
{{10086}}替换成<span class='changeColor' onclick='showDialog("{{10086}}")'>{{10086}}</span>
{{1}}替换成<span class='changeColor' onclick='showDialog("{{1}}")'>{{1}}</span>

首先找出来所有的{{}}内容然后去重
let str = Array.from(new Set(val.match(/\{\{(.+?)\}\}/g)))
然后便利这个数组进行全局替换

_.each(str,function(item){ 
    matchedVariable = matchedVariable.replace(new RegExp("(\\{\\{"+item.substring(2,item.length-2)+"\\}\\})",'g'),"<span class='changeColor' onclick='showDialog(\""+ item + "\")'>"+item+"</span>")
})

注意点:
1、由于我们使用的是变量进行替换,替换后的内容里面还有变量本身,所以需要在replace中使用new RegExp方法生成正则
2、同时我们的正则里面需要匹配{{}},而且{{}}中存在数字,例如{{10086}}{{1}},在正则看来{10086}表示前面的字符出现10086遍,就是{出现10086遍,为了避免这种错误所以只能进行转义,写成\{\{10086\}\}\{\{\1}\}
3、但是写成\{\{10086\}\}\{\{\1}\}这个无法通过eslint,同时new RegExp中也不可以出现特殊字符,认为\是违法的,所以要在所有的\的前面再加一个\,最终的写法就成了\\{\\{10086\\}\\}
4、逆向解释:我们的正则是\\{\\{item\\}\\},new RegExp之后会变成/\{\{item\}\}/g,里面的item也会通过new RegExp替换成变量对应的值,然后通过replace进行替换

posted @ 2021-03-28 22:08  木-鱼  阅读(67)  评论(0编辑  收藏  举报