0

Another jQuery question for you guys.

Say I have a url of an image in my web page surrounded by square brackets.

[http://www.example.com/picture.jpg]

How could I, with jQuery transform that string like so...

[http://www.example.com/picture.jpg]

into...

<img src="http://www.example.com/picture.jpg" />

?

5
  • 1
    That depends on what you call an image. How do you know whether example.com/foo.php is an image? Do you care? Can you be certain everything in square brackets is an image path? Commented Oct 22, 2009 at 8:44
  • also, what do you start out with? the specific strings with the square brackets or do you want to convert any text on the page surrounded by square brackets into images? Commented Oct 22, 2009 at 8:45
  • @Dominic This is a very niche project and there won't be any other urls inside these brackets. @cobbal Basically, grab the url inside the brackets and append into the src of the img attribute. Commented Oct 22, 2009 at 8:51
  • can't you use [img][/img] instead of just square brackets? Commented Oct 22, 2009 at 8:52
  • @Natrium, not the point, but yes I could, as mentioned this is a very niche project. Commented Oct 22, 2009 at 8:53

1 Answer 1

1

I'd do something like this

$("some-selector").each(function(){
    $(this).html($(this).html().replace(/\[(http:.*?)\]/gi, function(str, p1){
        return "<img src='"+p1+"' />";
    }));
});

"some-selector" should try to pinpoint where these string occur. If there is nothing like it... just put "body" and see what happens :)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you but no joy I'm afriad
There was a mistake in it... I have to use $(this). Maybe it works now :)
So so close, thank you! - I get: <img src="[example.co.uk/wp-content/uploads/2009/10/virgin_media.jpg"> - Just need to get rid of the left bracket?
Ah! This guy know Regex X( stackoverflow.com/questions/1077541/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.