kramer65
kramer65

Reputation: 54013

Javascript regex for StackOverflow style kind of image tags?

I'm trying to mimic the style of the Stackoverflow way of handling images. So if there is an image in a text I put in a tag comprising of an image description and the image its uuid:

![image description][3f5e7278-425d-4e75-9beb-59b6770b46a7]

Using Javascript I now want to take a piece of text, get all occurrences of this tag, get the image description and the uuid, and replace the tag with the appropriate <img tag so I can load them in my Backbone view. I'm kind of a noob with regex though. So I started with this:

var text = 'First some normal text ![image description][3f5e7278-425d-4e75-9beb-59b6770b46a7] and some more text here. And yet another image tag here: ![other img descript.][41f4fd84-0489-4d7a-8923-24d472008655]';
var re = new RegExp('[!\[.*\]\[.+\]]');
var m = re.exec(text);
if (m == null) {
    alert(text);
} else {
    alert('found some occurrences, but what to do with it?');
}

So I did my first attempt at the regex, which doesn't seem to be correct. Secondly, I don't really know how to use it to get the image description and uuid from them.

Could anybody help me out with the regex and with how to get the image description and uuid from them? All tips are welcome!

[EDIT] Thanks to the answer from @Teneff I now made something like you see below. Unfortunately, this doesn't work as it always alerts null. Any idea what I'm doing wrong here?

function imgTagToHtmlTag(text) {
    var re = /!\[([^\]]+)\]\[([^\]]+)\]/g;
    var m;

    while ((m = re.exec(text)) != null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
    }
    alert(m);
    // View your result using the m-variable.
    // eg m[0] etc.
}

var text = 'First some normal text ![image description][3f5e7278-425d-4e75-9beb-59b6770b46a7] and some more text here. And yet another image tag here: ![other img descript.][41f4fd84-0489-4d7a-8923-24d472008655]';
imgTagToHtmlTag(text);

http://jsfiddle.net/ASJT6/

Upvotes: 0

Views: 64

Answers (1)

Teneff
Teneff

Reputation: 32148

You can match it like this:

var re = /!\[([^\]]+)\]\[([^\]]+)\]/g;

here's an example

edit: second example with the global modifier

edit 2: if we think about the uuid as an image source you can replace it like this:

var text_modifited = text.replace(re, '<img src="$2" alt="$1" />')

jsFiddle example

Upvotes: 2

Related Questions