简体   繁体   English

javascript字符串正则表达式替换引号之间的字符串

[英]javascript string regex to replace a string between quotes

i want to replace all the src attribute inside a string of HTML adding a '?a' at the end of the url to fix a caching issue that i'm having. 我想替换HTML字符串中的所有src属性,并在url的末尾添加“?a”以解决我遇到的缓存问题。

So far i got this: 到目前为止,我得到了:

str.replace(/src=".*?"/gi, "src");

But i have no idea how to do the 2nd parameter to get what is matched and add the '?a' at the end. 但我不知道如何执行第二个参数来获取匹配的内容并在末尾添加“?a”。

Example: 例:

<img src="mysite.com/logo.png" /> should become <img src="mysite.com/logo.png" />应该成为

<img src="mysite.com/logo.png?a" />

Thank you in advance, Daniel! 提前谢谢你,丹尼尔!

The first problem is that you are matching the entire src attribute instead of what's within the src attribute. 第一个问题是您要匹配整个src属性,而不是src属性中的内容。

The second problem is that you aren't putting the match into your replacement. 第二个问题是您没有将匹配项放入替换项中。

This would be the correct regex: 这将是正确的正则表达式:

str.replace(/src="(.*?)"/gi, 'src="$1?a"')/;

Adding brackets around the match .*? 在比赛周围加括号.*? makes sure you match just that part instead of the whole regex, adding $1 into the second parameter makes sure you put the match back into the replacement. 确保只匹配该部分而不是整个正则表达式,在第二个参数中添加$1可以确保将匹配项放回替换项中。

You also have to re-enter src="" into the replacement, because the whole regex match will be replaced. 您还必须重新输入src=""到替换项中,因为整个正则表达式匹配项将被替换。

You can use this /src="(.*?)"/gi regex to find and replace the content. 您可以使用此/src="(.*?)"/gi regex查找并替换内容。 在此处输入图片说明

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

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