How can I replace a regex substring match in Javascript ?

How can I replace a regex substring match in Javascript ?

Asked on January 4, 2019 in Regex.
Add Comment


  • 2 Answer(s)

    To replace a regex substring match in Javascript use this:

    var str = 'asd-0.testing';
    var regex = /(asd-)\d(\.\w+)/;
    str = str.replace(regex, "$11$2");
    console.log(str);
    

    Else  to check any other digits in the string use this:

    var str = 'asd-0.testing';
    var regex = /\d/;
    str = str.replace(regex, "1");
    console.log(str);
    
    Answered on January 4, 2019.
    Add Comment

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

    var str = 'asd-0.testing';
    var regex = /(asd-)\d(\.\w+)/;
     
    if (str.match(regex)) {
      str = str.replace(regex, "$1" + "1" + "$2");
    }
    
    Answered on January 4, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.