如何在 Javascript 中替换正则表达式子字符串匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3598042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:23:32  来源:igfitidea点击:

How can I replace a regex substring match in Javascript?

javascriptregexreplacesubstring

提问by dave

var str   = 'asd-0.testing';
var regex = /asd-(\d)\.\w+/;

str.replace(regex, 1);

That replaces the entire string strwith 1. I want it to replace the matched substring instead of the whole string. Is this possible in Javascript?

替换整个字符串str1。我希望它替换匹配的子字符串而不是整个字符串。这在 Javascript 中可能吗?

回答by Amarghosh

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "");
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);

回答by dave

using str.replace(regex, $1);:

使用str.replace(regex, $1);

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "" + "1" + "");
}

Edit: adaptation regarding the comment

编辑:关于评论的改编

回答by Félix Saparelli

I would get the part before and after what you want to replace and put them either side.

我会在你想要更换的东西前后拿到零件,然后把它们放在两边。

Like:

喜欢:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

var matches = str.match(regex);

var result = matches[1] + "1" + matches[2];

// With ES6:
var result = `${matches[1]}1${matches[2]}`;

回答by Lantanios

I think the simplest way to achieve your goal is this:

我认为实现目标的最简单方法是:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `${anyNumber}`);