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. sql語句 - 如何在mysql中批量添加用戶?2. 怎么php怎么通過數組顯示sql查詢結果呢,查詢結果有多條,如圖。3. 老師們php,插入數據庫mysql,都是空的,要怎么解決4. 求大神支招,php怎么操作在一個html文件的<head>標記內添加內容?5. php點贊一天一次怎么實現6. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現存在即更新應該使用哪個標簽?7. PHP類屬性聲明?8. 致命錯誤: Class ’appfacadeTest’ not found9. phpstady在win10上運行10. 在應用配置文件 app.php 中找不到’route_check_cache’配置項
