javascript - Add span to specific words -


i trying add span specific word this:

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

here fiddle. tried using solution saw here not seem work. idea why? thank you

you're confusing regular expression literals , strings.

use create regex :

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

a regular expression literal :

/(something)/ 

there's no quote. literal, can't build code, that's why must use regexp constructor.

a side note : replacement yould made lighter and, more importantly, dryer using html variant taking function callback :

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

Comments