javascript - 這個正則表達式為什么總是只能替換掉一個字符串??
問題描述
我是想把雙大括號里的包括字符串替換成真正的值,但是總是只能替換掉一個,不知道為什么?
var tpl = ’/cube_xinbao_dial_result/{{report_type}}/{{query}}’;var data = {report_type:1, query: ’2323’}function render(tpl, data){ var re = /{{([^}]+)?}}/g; var match = ’’; while(match = re.exec(tpl)){tpl = tpl.replace(match[0],data[match[1]]); } return tpl;}console.log(render(tpl,data));
問題解答
回答1:ad
回答2:String.replace 也支持正則表達式當作參數哦,給你改寫了一下
var tpl = ’/cube_xinbao_dial_result/{{report_type}}/{{query}}’;var data = {report_type:1, query: ’2323’}function render(tpl, data){ var re = /{{([^}]+)?}}/g; return tpl.replace(re, function($0, $1, $2){if( $1 in data ){ return data[$1];}else{ return '[DATA.'+ $1.toUpperCase() + ']'; //如果沒有,提示標簽錯誤} });}console.log(render(tpl,data));/* /cube_xinbao_dial_result/1/2323*/console.log(render(tpl,{query:1234}));/* /cube_xinbao_dial_result/[DATA.REPORT_TYPE]/1234*/
如果執意要使用你原來的方式,需要取消掉全局參數g
var tpl = ’/cube_xinbao_dial_result/{{report_type}}/{{query}}’;var data = {report_type:1, query: ’2323’}function render(tpl, data){ var re = /{{([^}]+)?}}/; //不要全局匹配就可以 var match = ’’; while(match = re.exec(tpl)){tpl = tpl.replace(match[0],data[match[1]]); } return tpl;}console.log(render(tpl,data));/* /cube_xinbao_dial_result/1/2323*/回答3:
RegExp對象,有個屬性,lastIndex,代表一個整數,標示開始下一次匹配的字符位置。。當exec第一次執行成功后,lastIndex為匹配項位置+1。正因為這樣,再次調用才會會獲得下一個匹配項。回到你這個例子,第一次循環后,re的lastIndex為40,而此時tpl變為了tpl='/cube_xinbao_dial_result/1/{{query}}'顯然你要匹配的query的位置是在40之前的,所以再次匹配時失敗,exec返回null,循環跳出。
回答4:var tpl = ’/cube_xinbao_dial_result/{{report_type}}/{{query}}’;var data = {report_type:1, query: ’223’}function render(tpl, data){ var re = /{{([^}]+)?}}/g; var tpl2=tpl; tpl.match(re).forEach(function (val) {tpl2= tpl2.replace(val,data[val.substring(2,val.length-2)]); }); return tpl2;}console.log(render(tpl,data));
輸出結果
/cube_xinbao_dial_result/1/223
相關文章:
1. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. 在應用配置文件 app.php 中找不到’route_check_cache’配置項3. html按鍵開關如何提交我想需要的值到數據庫4. mysql取模分表與分表5. gvim - 誰有vim里CSS的Indent文件, 能縮進@media里面的6. HTML 5輸入框只能輸入漢字、字母、數字、標點符號?正則如何寫?7. 跟著課件一模一樣的操作使用tp6,出現了錯誤8. PHP類屬性聲明?9. objective-c - ios 怎么實現微信聯系列表 最好是swift10. javascript - 請教如何獲取百度貼吧新增的兩個加密參數
