JQuery: how to replace all between certain characters?

后端 未结 2 920
予麋鹿
予麋鹿 2020-12-06 23:32

I have searched for a general solution to this but only find answers to peoples specific questions.

Basically, I want to know how to generally use .replace() to repl

2条回答
  •  误落风尘
    2020-12-07 00:17

        String.prototype.replaceBetween = function(opentag, closetag, replacement) {
          var read_index = 0;
          var open_index = 0;
          var close_index = 0;
          var output = '';
    
          while ((open_index = this.indexOf(opentag, read_index)) != -1) {
            output += this.slice(read_index, open_index) + opentag;
            read_index = open_index + opentag.length;
    
            if ((close_index = this.indexOf(closetag, read_index)) != -1) {
              if (typeof replacement === 'function') {
                output += replacement(this.substring(open_index + opentag.length, close_index - 1)) + closetag;
              } else {
                output += replacement + closetag;
              }
              read_index = close_index + closetag.length;
            }
          }
    
          output += this.slice(read_index);
    
          return output
        };
    
        var mydiv = document.getElementById("mydiv");
        var html = mydiv.innerHTML;
        html = html.replaceBetween("", "", "hello");
        html = html.replaceBetween("", "", function(body) {
          return body + ' world';
        });
        mydiv.innerHTML = html;
    The begining...for and bar... the end.

提交回复
热议问题