Denny Denny - 2 months ago 16x
Javascript Question

Cannot use $2 backreference in regex replace

I'm trying to make a javascript calculator using string.replace regex but I'm stuck on a problem.

For example my input is

, I'm trying to replace the k with

So, I've made this regex that tries to replaces all occurences with the index of the letter
in the string

var answer = "10k".replace(/(\d+(?:[.,]+\d+)?)([kmbt])/gi, "kmbt".indexOf("$2"));

When I console.log this, it returns -1, which is not what I want.

So changing the regex a bit to:
var answer = "10k".replace(/(\d+(?:[.,]+\d+)?)([kmbt])/gi, "$2");
It will correctly return

What I want it to return is
which is the position of the letter k in the string "kmbt". With this position I want to continue calculating but that is currently not relevant with this problem.

The problem is that apparently I cannot use a function in the 'replace' part of the regex.

Does anyone know a solution to this problem or how I can use functions in the 'replace' part?


You cannot make modifications directly in the regex, so you have to add a function as argument to the 'replace' part where you can make modifications with the result!

var answer = rsn.replace(/(\d+(?:[.,]+\d+)?)([kmbt])/gi, function(match, p1, p2) {
// do something with p1 and p2 and return something
return p1 + p2 // for example


You can use a function to replace strings like so:

"10k".replace(/(\d+(?:[.,]+\d+)?)([kmbt])/gi, function(match, p1, p2) {
    return p2;

p1 and p2 correspond to "$1" and "$2" in a normal replace. Any additional transformations or calculations can take place in the function before returning a result. In order to find the index of p2 in the string "kmbt", this should work:

"10k".replace(/(\d+(?:[.,]+\d+)?)([kmbt])/gi, function(match, p1, p2) {
    return "kmbt".indexOf(p2);

You can read more about how to do this here.