How to replace a picture address in a string with a regular expression in JavaScript

Source: Internet
Author: User
Tags expression log regular expression

A problem was encountered today in development: how do I replace the SRC values of all the IMG tags contained in an HTML string?

The solution that comes to mind is:

Content.replace (/]*src=[']] ([^ ' "]+) [^>]*>/gi, function (match) {

Console.log (match);

});

The output results are:

Get the entire IMG tag, but I'm expecting a URL in src so I can just return the new address in the function (match).

So, it's stuck here ...

Later, through google search keyword "javascript replace callback", found in StackOverflow "replace callback function with matches" to know the function (match) There are other parameters (see developer.mozilla.org).

Then, the problem is solved by changing to the following code.

Content.replace (/]*src=[']] ([^ ' "]+) [^>]*>/gi, function (match, capture) {

Console.log (Capture);

});

Output results:

Http://static.cnblogs.com/images/logo_small.gif

Get!

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.