jQuery / Javascript replace multiple occurences not working -
i'm trying replace multiple occurrences of string , nothing seems working me. in browser or when testing online. going wrong?
str = '[{name}] happy today data-name="[{name}]" won match today. [{name}] made 100 runs.'; str = str.replace('/[{name}]/gi','john'); console.log(str);
i got example here, , wont work.
you must not quote regexes, correct notation be:
str = str.replace(/\[{name}\]/gi,'john');
also, have escape []
, because otherwise content inside treated character class.
updating fiddle accordingly makes work.
there 2 ways declaring regexes:
// literal notation - preferred option var re = /regex here/; // via constructor var re = new regexp('regex here');
Comments
Post a Comment