Javascript regex replace is not working sometimes -
i using regex search words same , replace same ones. replaced word changes original word time time. i'm not sure why.
here code.
function censor(word, string){ var newstring = ''; var replacestring = ''; var rand = math.floor(math.random() * 10) + 1; for(var x = 0 ; x < word.length ; x++){ switch (rand) { case 1: replacestring += '!'; break; case 2: replacestring += '@'; break; case 3: replacestring += '#'; break; case 4: replacestring += '$'; break; case 5: replacestring += '%'; break; case 6: replacestring += '^'; break; case 7: replacestring += '&'; break; case 8: replacestring += '*'; break; case 9: replacestring += '('; break; case 10: replacestring += ')'; break; } var rand = math.floor(math.random() * 10) + 1; } newstring = string.replace(new regexp(word,'g'), replacestring); return newstring; } var string = censor('damn', 'omg damn smart, damn !'); console.log(string); here of results unexpected.
- omg @%damn smart, @%damn !
- omg damn&& smart, damn&& !
there few sequences in replacement string expanded:
$&, entire match$`, string before match$', string after match$d(d digit), captured group @ index$$, single$
your random generator producing $& (and possibly $$). change
replacestring += '$'; to
replacestring += '$$'; and things should work properly.
Comments
Post a Comment