字符串操作大家应该会经常遇到,今天试着写了一个通用的字符串匹配方法,基本能用,记这里备忘。
使用场景
截取指定字符串前/中/后的字符,可匹配多个。
源码
String.prototype.stringMatch = function(templ, key,innerReg) {
var str = this,
keys = [],
res = {},
regs = {
divide: /\$\{([^\}]*)\}/g,
sensitive: /\?|\=|\|\^|\$|\*|\(|\)|\||\{|\}|\[|\]/g,
blank: /\r|\n|\t/g
},
nearby = templ.replace(regs.divide, function($0, $1) {
keys.push($1)
return ','
}).split(','),
trimSens = function(s) {
return s.replace(regs.sensitive, function($0) {
return '\\' + $0;
})
};
for (var i &#61; 0; i var reg &#61; new RegExp("(?<&#61;" &#43; trimSens(nearby[i] || &#39;&#39;) &#43; ")" &#43; (innerReg || ".*") &#43; "(?&#61;" &#43; trimSens(nearby[i &#43; 1] || &#39;&#39;) &#43; ")", "mg"),
val &#61; str.replace(regs.blank, &#39;&#39;).match(reg);
if (val) {
res[keys[i]] &#61; val[0];
}
}
return key ? res[key] : res;
};
//测试:
var str&#61;"字符串操作大家应该会经常遇到",
teml&#61;"字符串操作${key1}应该会${key2}遇到",
res&#61;str.stringMatch(teml);
document.write(JSON.stringify(res)); // &#61;> {key1:"大家",key2:"经常"}
使用方法场景一&#xff1a;路由参数获取var str&#61;"https://denghao.me/a/hello.html?v&#61;100",
teml&#61;"https://denghao.me/a/${name}.html?v&#61;${version}",
res1&#61;str.stringMatch(teml);
console.log(res1); // &#61;> {name:"hello",version:"100"}场景二&#xff1a;网页源码解析var str&#61;&#96;
微信小程序“拍照识图”上线... ...