How can I replace a regex substring match in Javascript?

后端 未结 4 1773
梦如初夏
梦如初夏 2020-11-29 21:06
var str   = \'asd-0.testing\';
var regex = /asd-(\\d)\\.\\w+/;

str.replace(regex, 1);

That replaces the entire string str with

4条回答
  •  一生所求
    2020-11-29 21:26

    using 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");
    }
    

    Edit: adaptation regarding the comment

提交回复
热议问题