var str = "1-2";
var arr = ["", "a", "b"];
I would like to replace 1 with “a”, and 2 with “b”, here is my code. But it didn’t work.Pls help me out.
str = str.replace('(\d)-', arr["$1"]+"-");
str = str.replace('-(\d)', "-"+arr["$1"]);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use an anonymous function:
Note, that this will only replace one occurence (commenters were faster that me editing; you might want to use the
gmodifier for the regex in order to repeat replacing until the regex doesn’t match).The anonymous function’s arguments are the full matched string and capture groups (if any).