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"]);
Use an anonymous function:
var arr = [ /* ... */ ];
str = str.replace(/\d/, function(match) {
return arr[match];
});
Note, that this will only replace one occurence (commenters were faster that me editing; you might want to use the g modifier 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).
var str = "1-2";
var arr = ["", "a", "b"];
str = str.replace(/(\d)-/, function (mathchedText,$1,offset,str) {
return arr[$1] + "-"
});
str = str.replace(/-(\d)/,function (mathchedText,$1,offset,str) {
return "-" + arr[$1]
});
document.write(str);
Here's the working code: http://jsfiddle.net/HsQC7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With