How can I replace a regex substring match in Javascript?

后端 未结 4 1771
梦如初夏
梦如初夏 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]}`;
    
    0 讨论(0)
  • 2020-11-29 21:20
    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);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-29 21:27

    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, `$1${anyNumber}$3`);
    
    0 讨论(0)
提交回复
热议问题