利用正则表达式我们可以很容易的匹配到一些所需的字符串,当我们需要对匹配到的一些字符进行处理时,可以参考以下做法。
let str ="{"type":2,"tagName":"script","attributes":{"src":"http://code.jquery.com/js/jquery-latest.js","link ":"http://test.com/home/index/page.html"},"childNodes":[],"id":13}"
Q1:将字符串中的tagName替换成TagName ?
let reg = new RegExp ("tagName","g")
let newStr = str.replace(reg,"TagName ")
Q2 : 将两个不同的字符串替换成一个:http://code.jquery.com/js以及 http://test.com/index替换成 //www.greatytc.com/js 和//www.greatytc.com/index?
let url1 = "http://code.jquery.com", url2 = "http://test.com"
let reg = new RegExp(${url1}(/js)|${url2}(/index)
,"g")
let newStr = str.replace(reg,"//www.greatytc.com"+"2")
Q3: 对正则匹配出来的值进行处理?
let str1 = "{"type":2,"tagName":"script","attributes":{"src":"//www.greatytc.com/js/jquery-latest.js","link ":"//www.greatytc.com/index/page.html"},"childNodes":[],"id":13}" ;
let url3 = //www.greatytc.com ;
//匹配出以url3开头 .js 和.html 结尾的字符,并删除url3返回;
let regExp = new RegExp(${url3}(?!(\\.js|\\.html)).+?(\\.js|\\.html)
, "g")
let newStr = str1.replace(regRxp,replaeFun)
//replaeFun是一个函数方法,1){
let p = $1;
return p.replace(url3,"")
}