Replace the image address img label with a regular expression

  • 2020-03-29 23:58:41
  • OfStack

The solution that came to mind was:


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

The output is:


<img src="//www.jb51.net/images/logo.gif" alt="" width="142" height="55" />

I get the entire img tag, but I expect the url in SRC, so I simply return the new address in function(match).
So, stuck here...
Later, a Google search for the keyword "javascript replace callback" turned up "replace callback function with matches" on stackoverflow, and it became clear that function (match) had other parameters

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


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

Output results:


//www.jb51.net/images/logo.gif


Related articles: