Dmitri
Dmitri

Reputation: 2467

jQuery preg replace

Hi again dear comminity!

To make it short, I have a textbox, where you can paste <img> tags, which look like this: <img src="123.jpg" />.

Is there any way to make these <img> look this: <img src="img/upload/username/123.jpg" /> using jQuery .replace() or something like this ? Or should I use PHP function instead ?

I have tried to find out what jQuery .match() returns for some regual expression:

x = text.match(/\<img src="(.*)" \/>\$/);
alert(x);

,but it returns odd things, when there are more than one <img> tag.

Thank you for your help!

Upvotes: 1

Views: 4244

Answers (5)

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

Not tested...

$('#text').change(function(){

    $('img').each(function(){
        $(this).attr('src', '/img/upload/username/' + $(this).attr('src'));
    });

});

If you would like to do this on server side with PHP you can just replace like this, no need for regex...

$text = str_replace('src="', 'src="/img/upload/username/', $text);

Or if you would like to use regexp...

$text = preg_replace('#"(.*?)\.jpg"#is', '"/img/upload/username/\\1.jpg"', $text);

Upvotes: 4

stema
stema

Reputation: 93036

Your regex returns not what you expect with more than one tag, because you use a greedy quantifier here:

x = text.match(/\<img src="(.*)" \/>\$/);
                             ^

To fix this try this:

x = text.match(/\<img src="(.*?)" \/>\$/);

I am not sure about your escaping ... . Normally you don't need to escape < and I also don't understand what the \$ is good for at the end. It is not in your string. If you want to have a anchor for string end then don't escape it, but if you want to be able to insert multiple tags, you can't use it at all.

Upvotes: 0

Karolis
Karolis

Reputation: 9572

but it returns odd things, when there are more than one tag.

I think it's the problem that you are not using a lazy match. Instead of (.*) use (.*?)

Upvotes: 1

Nightwolf
Nightwolf

Reputation: 951

The function you would like to use in jquery is .attr() and replace the content with whatever you like. Here is the tutorial page: http://api.jquery.com/attr/

Upvotes: 1

K6t
K6t

Reputation: 1845

var text    =   '<img src="img/upload/username/123.jpg" />';
x = text.match(/\<img src="(.*)" \/\>$/);
alert(x);

now u ll get??

match(/\<img src="(.*)" \/\>$/);
                          ^
                          |-----------------Becarefull about about ur special char dude....

Upvotes: 0

Related Questions