javascript - how to use regex with variables instead of string? -


asked few times, can't work.

i'm doing lot of these on script replacing various class names.

label.classname.replace(/(?:^|\s)ui-icon-checkbox-on(?!\s)/g , ' ui-icon-globe'); 

and wanted replace replace call generic function being passed string ui-icon-checkbox-on , returns regex object handle replace.

however, not working = it's not replacing anything:

var foo = function (classname) {   return new regexp("(?:^|\s)" + classname + "(?!\s)", "g"); };  label.classname = label.classname.replace(foo("ui-icon-checkbox-on"), ' ui-icon-globe'); 

and i'm @ loss trying understand why.

question:
how correctly create regex object, , use replace string string?

thanks!

ps: , no, don't want use jquery :-)

you need escape escaped regexp sequences:

var foo2 = function (classname) {   return new regexp("(?:^|\\s)" + classname + "(?!\\s)", "g");   //----------------------^^^---------------------^^^ }; 

your original function return:

foo("asd") // returns: /(?:^|s)asd(?!s)/g 

but we're after this:

foo2("asd") // returns: /(?:^|\s)asd(?!\s)/g 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -