JavaScript 替換所有匹配內容


  • 由於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)

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM