简体   繁体   English

正则表达式替换仅适用于最后一场比赛

[英]Regex Replace only working on Last Match

I'm trying to replace the src of a number of image html elements in plain text (before they are rendered in the browser). 我正在尝试用纯文本替换许多图像html元素的src(在浏览器中呈现它们之前)。

Here's what I have so far 这是我到目前为止的

 var base = './images'; var sample = '<p><img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img src="3.png" alt="image-1"></p>'; sample = sample.replace(/(<img.+src=")(?!http:\\/\\/)(.*?)"/g, '$1' + base + '/$2"'); $('pre').text(sample); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre></pre> 

However it only replaces the src of the last image element. 但是,它仅替换最后一个图像元素的src。 What am I missing here? 我在这里想念什么?

The greedy match in <img.+src is catching everything between the first img and the last src ; <img.+src的贪婪匹配捕获了第一个img和最后一个src之间的所有内容; your $1 is therefore 因此,您的$1

<img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img src="

Change to a non-greedy match: 更改为非贪婪匹配:

sample = sample.replace(/(<img.+?src=")(?!http:\/\/)(.*?)"/g, '$1' + base + '/$2"');

 var base = './images'; var sample = '<p><img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img src="3.png" alt="image-1"></p>'; sample = sample.replace(/(<img.+?src=")(?!http:\\/\\/)(.*?)"/g, '$1' + base + '/$2"'); $('pre').text(sample); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre></pre> 

As @elclanrs metions in a comment, it seems like you are using the wrong approach here. 正如@elclanrs在评论中提到的那样,似乎您在这里使用了错误的方法。 Changing it trough the DOM via jQuery or the like seems a more appropriate method. 通过jQuery等通过DOM更改它似乎是更合适的方法。

That being said, if, for some reason, this is the opportune way to solve it (I do not know all the variables), you should solve it by making the RegEx more explicit. 话虽如此,如果由于某种原因这是解决它的合适方法(我不知道所有变量),则应通过使RegEx更明确地解决它。 Greedy matching generally performs the best , and having to use lazy evaluation (non-greedy) is generally a sign that either your RegEx is not specific enough, or that you are using RegEx to solve something that should not be solved with RegEx. 贪婪的匹配通常表现最佳 ,并且必须使用惰性评估(非贪婪)通常表明您的RegEx不够具体,或者您正在使用RegEx解决某些不应由RegEx解决的问题。 This should do the trick somewhat: 这应该可以解决问题:

 var base = './images'; var sample = '<p><img src="1.png" alt="image-1"></p><p><img src="2.png" alt="image-1"></p><p><img alt="image-1" src="3.png"></p>'; sample = sample.replace(/(<img[^>]+src=")(?!http:\\/\\/)([^"]+)"/g, '$1' + base + '/$2"'); $('pre').text(sample); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre></pre> 

Not exactly sure I'm doing the code tags correct though. 不确定我是否正确地执行了代码标记。 Still learning to use those. 还在学习使用那些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM