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 con开发者_Python百科figurations 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??
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.
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.
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]);
精彩评论