[英]Javascript replace, ignore the first match
I have the following script in javascript 我在javascript中有以下脚本
var idText;
var idText1;
idText = "This_is_a_test";
idText1 = idText.replace(/_/g, " ");
alert(idText1);
When I show idText1, it replaces all of the underscores and puts in a space where they were. 当我显示idText1时,它将替换所有下划线并将其放在空格中。 However, I am trying to keep the very first underscore, so I get "This_is a test". 但是,我试图保留第一个下划线,因此我得到“ This_is a test”。 Is this possible at all? 这有可能吗?
It is certainly possible, here is one option: 当然有可能,这是一种选择:
var n = 0;
idText1 = idText.replace(/_/g, function($0) {
n += 1;
return n === 1 ? $0 : " ";
});
This uses a callback for the replacement that increments a counter for each match, and replaces the first match with the original text by checking the value of that counter. 这将使用回调进行替换,从而为每个匹配项增加一个计数器,并通过检查该计数器的值将第一个匹配项替换为原始文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.