The example of this article describes the method of replacing the image address (img src) in the string with JavaScript regular expression. Share it with everyone for your reference, the details are as follows:
I encountered a problem during development today: How to replace the src value of all img tags contained in an HTML string?
The solution I first thought of is:
content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match) { console.log(match); });
The output result is:
<img src="http://www.php.cn/images/logo.gif" alt="" width="142" height="55" />
What I get is the entire img tag, but what I expect is URL in src, so just return the new address in function(match).
So, I’m stuck here. . .
Later, I searched Google for the keyword "javascript replace callback" and found "replace callback function with matches" in stackoverflow, and then I learned that function (match) has other parameters (see developer.mozilla.org for details) ).
Then, change to the following code and the problem will be solved.
content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) { console.log(capture); });
Output result
http://www.php.cn/images/logo.gif
Done!
I hope this article will be helpful to everyone in JavaScript programming.
For more related articles on how to replace image addresses (img src) in strings with JavaScript regular expressions, please pay attention to the PHP Chinese website!