Method of replacing picture address of img src in string with JavaScript regular expression

  • 2021-07-10 18:42:24
  • OfStack

This article illustrates the method of replacing picture address (img src) in string with JavaScript regular expression. Share it for your reference, as follows:

Today, I encountered a problem in my development: How do I replace the src values of all img tags contained in an HTML string?

The solution that came to mind at first was:


content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match) {
  console.log(match);
});

The output is:

<img src="https://www.ofstack.com/images/logo.gif" alt="" width="142" height="55" />

What I get is the entire img tag, but what I expect is the URL in src, so I just need to return the new address in function (match).

So, it's stuck here. . .

Later, through Google search keyword "javascript replace callback", "replace callback function with matches" was found in stackoverflow, only to know that function (match) has other parameters (see developer. mozilla. org for details).

Then, change to the following code, and the problem is solved.


content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
  console.log(capture);
});

Output:


https://www.ofstack.com/images/logo.gif

Done!

PS: Here are two very convenient regular expression tools for your reference:

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg

More readers interested in JavaScript can check out the topics of this site: "JavaScript Regular Expression Skills Encyclopedia", "JavaScript Replacement Operation Skills Summary", "JavaScript Search Algorithm Skills Summary", "JavaScript Data Structure and Algorithm Skills Summary", "JavaScript Traversal Algorithm and Skills Summary", "json Operation Skills Summary in JavaScript", "JavaScript Error and Debugging Skills Summary" and "JavaScript Mathematical Operation Usage Summary"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: