- 由于JavaScript 的 replace 只能替換一次,因此另外撰寫一個能現替換全部匹配內容方法,代碼如下:
/* 把 content 中所有的 searchValue 替換為 replaceValue */ function replaceAll(content,searchValue,replaceValue){ while (content.indexOf(searchValue)>-1) { content = content.replace(searchValue,replaceValue); } return content; }
- 為什么不使用正側運算式來替換?
- 因為實際操作中發現 searchValue 的內容太大的時候使用正側運算式替換會出錯
- 我的場景是把 html 頁面 img 中的base64 xxx1,base64 xxx2 圖片內容替換為 [image1][image2] 這樣的占位符時,如果使用正則運算式就出錯
- 附上一般情況下使用正側運算式的替換方法
content.replace(new RegExp(searchValue,'g'),replaceValue)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/149824.html
標籤:JavaScript
下一篇:02.JS資料型別與資料型別轉換
