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) {

The output is:

<img src="//" 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) {

Output results:


Related articles: