Javascript replace, ignore first match

I have the following script in javascript

var idText;
var idText1;
idText = "This_is_a_test";
idText1 = idText.replace(/_/g, " ");
alert(idText1);

When I show idText1, it replaces all underscores and places in the space where they were. However, I am trying to keep the first underscore, so I get "This_is test". Is this even possible?

0
source share
1 answer

This is certainly possible, here is one of the options:

var n = 0;
idText1 = idText.replace(/_/g, function($0) {
    n += 1;
    return n === 1 ? $0 : " ";
});

It uses a replacement callback that increments the counter for each match and replaces the first match with the source text, checking the value of that counter.

+3
source

All Articles