Home > Web Front-end > JS Tutorial > How to replace image address (img src) in string with JavaScript regular expression

How to replace image address (img src) in string with JavaScript regular expression

高洛峰
Release: 2017-01-14 09:48:42
Original
2223 people have browsed it

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=[&#39;"]([^&#39;"]+)[^>]*>/gi, function (match) {
  console.log(match);
});
Copy after login

The output result is:

<img src="http://www.php.cn/images/logo.gif" alt="" width="142" height="55" />
Copy after login

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=[&#39;"]([^&#39;"]+)[^>]*>/gi, function (match, capture) {
  console.log(capture);
});
Copy after login

Output result

http://www.php.cn/images/logo.gif
Copy after login

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!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template