JQuery的:如何更换所有的某些字符之间?(JQuery: how to replace all

2019-06-25 11:11发布

我已经寻找一个通用的解决方案,以这一点,但只找到答案,人民的具体问题。

基本上,我想知道如何一般采用.replace()来替换字符串,例如,在任何类型的字符之间的项目:

在替换之间的所有文字和包容性的ABC和XYZ如: abc text to be replaced xyz

或更换之间的所有文本和包容性的<img and />例如: <img src="image.jpg" />

任何人都可以帮我或点我在一个很好的土特的方向是什么?

谢谢! 让我知道如果我需要澄清更多。

Answer 1:

你所寻找的被称为正则表达式。 欲了解更多信息,可以访问这样的网站: http://www.regular-expressions.info/

请注意,正则表达式不是特定为JavaScript。

为了您的具体的例子:

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

。 指任何字符,以及+是指一个或多个正好。

如果你有一个以上的替代办,试试:

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

G代表一般,和? 是懒惰量词,这意味着它将在XYZ的字符串中的下occurence停止。



Answer 2:

  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> 



文章来源: JQuery: how to replace all between certain characters?