Search code examples
javascriptregexarraysobject-type

Regex: are digit matches returned as string or number?


Yesterday I was answering a question on stackoverflow, and there's something I don't understand in my own answer...

References: the thread in question, and my fiddle

Here is the code from my answer:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function($0,$1){return params[parseInt($1)];});

Now, what surprises me is that the following code works too:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function($0,$1){return params[$1];});

My question: how come parseInt is not needed? At what point does JavaScript convert $1 into a number? Is it in the regex, or in the array?


Solution

  • That is because javascript reads indexes as a string

    array[1], will be converted to array['1'] before being read

    The same way object['first'] will work