Ad

Javascript Regex Replace Is Not Working Sometimes

- 1 answer

I am using regex to search for all words that is the same and replace the same ones. However the replaced word changes back to the original word from time to time. I'm not sure why.

Here is the 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 so smart, damn !');
console.log(string);

Here are some of the results that are unexpected.

  • Omg @%damn so smart, @%damn !
  • Omg damn&& so smart, damn&& !
Ad

Answer

There are a few sequences in the replacement string that are expanded:

  • $&, the entire match
  • $`, the string before the match
  • $', the string after the match
  • $d (d is any digit), the captured group at that index
  • $$, a single $

Your random generator is producing $& (and possibly $$). Just change

replaceString += '$';

to

replaceString += '$$';

and things should work properly.

Ad
source: stackoverflow.com
Ad