简体   繁体   中英

How to replace image URL(plain text) with Regex

The javascript code will be change image URL(plain text), for example :

http://www.sstatic.net/stackoverflow/img/apple-touch-icon.png

to be show like this :

在此处输入图片说明


and this is the code I wanted to use :

var isImgUrl= /(https?:\/\/.*\.(?:png|jpg|gif))/i;
var txt=document.getElementById('comment');
txt.innerHTML=txt.innerHTML.replace(isImgUrl,'<img src=" [how to insert the image URL here from regex?] "/>');

please help me to fix the codes above

by the way, what the regex(on var isImgUrl) is already correct?

You're almost there, Herry. When you're doing replacements, there are some metacharacters available for you in the replacement string. $1 will insert the first matched group, $2 will insert the second matched group, and so on. However, in your case, you can use the even more general $& , which will insert the entire matched regex, so you can even drop the unnecessary group in your regex:

var isImgUrl= /https?:\/\/.*\.(?:png|jpg|gif)/i;
var txt=document.getElementById('comment');
txt.innerHTML=txt.innerHTML.replace(isImgUrl,'<img src="$&"/>');

I'm guessing here, but you probably also want to include the common JPEG extension .jpeg (as well as the shorter .jpg ).

I also you suspect you want to replace all such matches; what you have will only replace the first. To replace all matches, specify the g modifier to the regex as well. So taking all this in mind, your regex becomes:

var isImgUrl= /https?:\/\/.*\.(?:png|jpg|jpeg|gif)/ig;

Except wait! There's more. If you do multiple replacements this way, you'll run into trouble because of the greedy nature of repetition operators. So try the above regex on this string:

"One picture: http://foo.com/a.jpg, two pictures: http://foo.com/b.jpg."

What you are expecting to get back is this:

"One picture: <img src="http://foo.com/a.jpg"/>, two pictures: <img src="http://foo.com/b.jpg">."

But what you'll actually get is this:

"One picture: <img src="http://foo.com/a.jpg, two pictures: http://foo.com.b.jpg">."

Whoops! What happened? Well, the .* is greedy ; that is, it will match as much as it possibly can. So it did, and it scooped up both images.

All you have to do is change it to lazy by adding a question mark after the repetition operator:

var isImgUrl= /https?:\/\/.*?\.(?:png|jpg|jpeg|gif)/ig;

Now it should work as expected! You can see it in action here:

http://jsfiddle.net/tMA6e/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM