Use a JavaScript Regular Expression to replace the image address (imgsrc) in a string

Source: Internet
Author: User
This article mainly introduces how to replace the image address (imgsrc) in a string with a JavaScript Regular Expression, and analyzes common tips and precautions for JS Regular Expression replacement in combination with examples, for more information about how to replace the image address (img src) in a string with a JavaScript regular expression, see the following example. We will share this with you for your reference. The details are as follows:

Today, I encountered a problem: how to replace the src value of all img tags contained in an HTML string?

The solution is as follows:

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

The output result is:

 

The entire img tag is obtained, but what I expect is the URL in src, so you only need to return the new address in function (match.

So, it's stuck here...

Later, I searched for the keyword "javascript replace callback" by Google and found "replace callback function with matches" in stackoverflow to know that function (match) has other parameters (for details, see pai.mozilla.org ).

Then, change the code below to solve the problem.

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

Output result

#images/logo.gif

Done!

I hope this article will help you design JavaScript programs.

For more information about how to replace the image address (img src) in a string with a JavaScript regular expression, see PHP!

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.