dav*_*ave 103 javascript regex replace substring
var str = 'asd-0.testing';
var regex = /asd-(\d)\.\w+/;
str.replace(regex, 1);
Run Code Online (Sandbox Code Playgroud)
替换整个字符串str用1.我希望它替换匹配的子字符串而不是整个字符串.这可能在Javascript中吗?
Ama*_*osh 130
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);
Run Code Online (Sandbox Code Playgroud)
或者,如果您确定字符串中没有任何其他数字:
var str = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);
Run Code Online (Sandbox Code Playgroud)
小智 54
使用str.replace(regex, $1);:
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
if (str.match(regex)) {
str = str.replace(regex, "$1" + "1" + "$2");
}
Run Code Online (Sandbox Code Playgroud)
编辑:关于评论的改编
Fél*_*lli 24
我会在你想要替换之前和之后得到它的部分,并把它们放在一边.
喜欢:
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]}`;
Run Code Online (Sandbox Code Playgroud)
我认为实现目标的最简单方法是:
var str = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150274 次 |
| 最近记录: |