2

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??

1
  • could you provide a real HTML sample you are trying to modify? Commented Jun 8, 2011 at 15:31

3 Answers 3

1

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.

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

Comments

0

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.

Comments

0

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]);

Comments

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.