Cornwell
Cornwell

Reputation: 3410

Add span to specific words

I am trying to add a span to a specific word like this:

var value = "eror";
var template = "/(" + value + ")/g";
$("#content").html($("#content").html().replace(template, '<span class="spell_error">$1</span>'));

Here is my fiddle. I tried using a solution I saw here but it does not seem to work. ANy idea why? Thank you

Upvotes: 1

Views: 225

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You're confusing regular expression literals and strings.

Use this to create your regex :

var template = new RegExp("(" + value + ")", 'g');

A regular expression literal is like this :

/(something)/

There's no quote. But as it is a literal, you can't build it with your code, so that's why you must use the RegExp constructor.

A side note : your replacement yould be made lighter and, more importantly, dryer by using the html variant taking a function as callback :

$("#content").html(function(_,html){
    return html.replace(template, '<span class="spell_error">$1</span>')
});

Upvotes: 6

Related Questions