This article mainly introduces how to replace the image address (imgsrc) in a string with a JavaScript Regular Expression, and analyzes common tips and precautions for JS Regular Expression replacement in combination with examples, for more information about how to replace the image address (img src) in a string with a JavaScript regular expression, see the following example. We will share this with you for your reference. The details are as follows:
Today, I encountered a problem: how to replace the src value of all img tags contained in an HTML string?
The solution is as follows:
content.replace(/]*src=['"]([^'"]+)[^>]*>/gi, function (match) { console.log(match);});
The output result is:
The entire img tag is obtained, but what I expect is the URL in src, so you only need to return the new address in function (match.
So, it's stuck here...
Later, I searched for the keyword "javascript replace callback" by Google and found "replace callback function with matches" in stackoverflow to know that function (match) has other parameters (for details, see pai.mozilla.org ).
Then, change the code below to solve the problem.
content.replace(/]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) { console.log(capture);});
Output result
#images/logo.gif
Done!
I hope this article will help you design JavaScript programs.
For more information about how to replace the image address (img src) in a string with a JavaScript regular expression, see PHP!