JavaScript Regular expression replace picture address img Tag

Source: Internet
Author: User

The solution that comes to mind is:

The code is as follows Copy Code

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

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

The code is as follows Copy Code


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


Output results:


/images/logo.gif


Later, Baidu and find a more good example

The code is as follows Copy Code

<script type= "Text/javascript" >
The idea is divided into two steps: the author (yanue).
1, matching out the image of the IMG tag (that is, match all the pictures), filter other unwanted characters
2. From the matching result (in the IMG tag) loop match out the picture address (that is, SRC attribute)
var str = "This is test string 123" and " 33! Matching picture (g means match all results I indicates case-sensitive)
var Imgreg =/|/>)/gi;
Match src attribute
var srcreg =/src=[' "]? ([^'"]*) [' "]?/i;
var arr = Str.match (Imgreg);
Alert (' array of all successfully matched pictures: ' +arr ');
for (var i = 0; i < arr.length; i++) {
var src = arr[i].match (srcreg);
Get Picture Address
if (Src[1]) {
Alert (' Matching picture address ' + (i+1) + ': ' +src[1]);
}
Of course you can also replace the SRC attribute
if (Src[0]) {
var t = src[0].replace (/src/i, "href");
Alert (t);
}
}
</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.