JQuery: how to replace everything between certain characters?

I was looking for a general solution for this, but found answers to specific questions from people.

Basically, I want to know how to usually use .replace () to replace elements between any characters in a string, for example:

Replace all text between and including abc and xyz, for example: abc text to be replaced xyz

or replace all text between and inclusive <img and /> for example: <img src="image.jpg" />

Can someone help me or point me towards a good game on this?

Thanks! Let me know if I need to clarify more.

+1
source share
2 answers

What you are looking for is called regular expressions. For more information, you can visit the site, for example: http://www.regular-expressions.info/

Please note that regular expressions are not JavaScript.

In your specific example:

 string.replace(/abc.+xyz/,"abc"+newString+"xyz"); 

. means any character, and + means one or more occurrences.

If you have a few notes, try:

 string.replace(/abc.+?xyz/g,"abc"+newString+"xyz"); 

g means total, and? this is a lazy quantifier, meaning that it will stop the next time xyz appears on the line.

+3
source

  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("<b>", "</b>", "hello"); html = html.replaceBetween("<b>", "</b>", function(body) { return body + ' world'; }); mydiv.innerHTML = html; 
 <div id="mydiv">The begining...<b>for</b> and <b>bar</b>... the end.</div> 
+2
source

Source: https://habr.com/ru/post/1479139/


All Articles