如何在Javascript中替换正则表达式子字符串匹配? [英] How can I replace a regex substring match in Javascript?
本文介绍了如何在Javascript中替换正则表达式子字符串匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var str = 'asd-0.testing';
var regex = /asd-(\d)\.\w+/;
str.replace(regex, 1);
用<替换整个字符串 str
code> 1 。我希望它替换匹配的子字符串而不是整个字符串。这可以在Javascript中使用吗?
That replaces the entire string str
with 1
. I want it to replace the matched substring instead of the whole string. Is this possible in Javascript?
推荐答案
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);
或者,如果您确定字符串中没有任何其他数字:
Or if you're sure there won't be any other digits in the string:
var str = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);
这篇关于如何在Javascript中替换正则表达式子字符串匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文