Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use $1 as index of an array in replace function

Tags:

javascript

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"]);
like image 509
Will Avatar asked Dec 30 '25 16:12

Will


2 Answers

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).

like image 166
Linus Kleen Avatar answered Jan 02 '26 08:01

Linus Kleen


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/

like image 41
robert Avatar answered Jan 02 '26 09:01

robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!