How can I replace a regex substring match in Javascript?

后端 未结 4 1780
梦如初夏
梦如初夏 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:08

    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]}`;
    

提交回复
热议问题