Adam
Adam

Reputation: 73

Javascript regular expressions: substituting variables

I need a hand to sub a variable into a regular expression

this line works fine:

subject = subject.replace(/<a title="Smile"><img.+?<\/a>/g, emoticons[1]);

I need switch the word "Smile" for a variable.

I have tried a few different configurations like:

subject = subject.replace(/<a title="'+emoLanguage[0]+'"><img.+?<\/a>/g, emoticons[1]);

but I can't get the variable to work.

Whats the trick??

Upvotes: 2

Views: 197

Answers (3)

aorcsik
aorcsik

Reputation: 15552

You have to use the RegExp object cobnstructor in such case:

var pattern = new RegExp('<a title="'+emoLanguage[0]+'"><img.+?</a>',"g");
subject = subject.replace(pattern, emoticons[1]);

Upvotes: 0

Martijn
Martijn

Reputation: 13622

Use the new Regexp() constructor to create the regular expression, instead of a literal regexp.

Note that you’ll have to properly escape your string, since many characters have special meaning in a regexp.

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95508

First I would say that you probably shouldn't use a regular expression to parse/fix HTML. That being said, this should work:

var re = new RegExp("<a title=\"" + emoLanguage[0] + "\"><img.+?</a>", "g");
subject = subject.replace(re, emoticons[1]);

A better solution would be to use jQuery. The solution is much prettier:

jQuery("a[title='" + emoLanguage[0] + "']").replaceWith(emoticons[1]);

This assumes that the data in emoticons[1] is HTML.

Of course, importing jQuery for just this little thing is probably overkill, but I'm sure that you'll find that it will probably make other things in your Javascript much more easier and elegant.

Upvotes: 1

Related Questions