javascript - How to replace $1 , $2 in string -
var params = ['tom' , 'harry']; var string = 'hello $1 , $2 how aa $1 , $2'; what tried
var params = ['tom' , 'harry']; var string = 'hello $1 ,$2 how aa $1 , $2'; var temp; for(var = 0; i<params.length ; i++) { temp = string.replace(/[$1]+/g,params[i]); } firefox console wrong output : "hello harry ,harry2 how aa harry , harry2"
final output : hello tom , harry how tom , harry
one solution:
string.replace(/\$1/g, params[0]).replace(/\$2/g,params[1]) more explanation:
the reason put $1 \$1 because $1, $2,... have special meaning inside regular expressions. considered special characters. e.g., if want search . (dot) in string cannot place . in regex because in regex . means match character inside string (including dot too); so, in order find . in string you've place(slash \) before dot, \. , inside regex, regex engine can find exact . character.
Comments
Post a Comment