JavaScript replace all matches

  • Since the replacement of JavaScript replace only once, so a write additional content can now replace all matching method, as follows:
    /*
    All of the content searchValue replaced replaceValue
    */ 
     function replaceAll(content,searchValue,replaceValue){
          while (content.indexOf(searchValue)>-1) {
            content = content.replace(searchValue,replaceValue);
          }
          return content;
        }
  • Why not replace the use of the positive side of the expression?
    • Because the practice found much time searchValue content of regular expressions to replace the side to be wrong
    • My scenario is base64 xxx1 img in the html page, base64 xxx2 picture content is replaced with [image1] [image2] when such a placeholder, if using regular expressions on the wrong
  • Generally attach replacement method using the positive side of the expression
    content.replace(new RegExp(searchValue,'g'),replaceValue)

     

Guess you like

Origin www.cnblogs.com/anyjs/p/12297431.html