Search code examples
javascriptregexreplacestr-replacereplaceall

How to replace $1 , $2 in string


var params = ['tom' , 'harry'];

var string = 'hello $1 and $2  how aa are you $1 and $2';

What i tried

var params = ['tom' , 'harry'];
var string = 'hello $1 ,$2  how aa are you $1 , $2';
var temp;
for(var i = 0; i<params.length ; i++)
{
  temp = string.replace(/[$1]+/g,params[i]);   
}

Firefox console wrong output : "hello harry ,harry2 how aa are you harry , harry2"

Final Output : hello tom and harry how are you tom and harry


Solution

  • One solution:

    string.replace(/\$1/g, params[0]).replace(/\$2/g,params[1])
    

    More explanation:

    The reason I put $1 as \$1 because $1, $2,... have special meaning inside regular expressions. They are considered as special characters. E.g., if you want to search . (dot) in your string then you cannot just place . in regex because in regex . means match any character inside string (including dot too); so, in order to find . in your string you've to place(slash \) before dot, like \. , inside regex, so that regex engine can find exact . character.