JavaScript – string regex backreferences

JavaScript – string regex backreferences

Asked on January 11, 2019 in Regex.
Add Comment


  • 3 Answer(s)

    To replace Pass a function as the second argument:

    str = str.replace(/(\$)([a-z]+)/gi, myReplace);
     
    function myReplace(str, group1, group2) {
      return "+" + group2 + "+";
    }
    

    In Javascript 1.3, according to mozilla.org.

    Answered on January 11, 2019.
    Add Comment

    In JavaScript – string regex backreferences use ESNext:

    let text = 'Visit http://lovecats.com/new-posts/ and https://lovedogs.com/best-dogs NOW !';
     
    text = text.replace(/(https?:\/\/[^ ]+)/g, (match, link) => {
      // remove ending slash if there is one
      link = link.replace(/\/?$/, '');
     
      return `<a href="${link}" target="_blank">${link.substr(link.lastIndexOf('/') +1)}</a>`;
    });
     
    document.body.innerHTML = text;
    
    Answered on January 11, 2019.
    Add Comment

    var text = “some string with an encoded ‘s’ in it”;
    text.replace(/&#(\d+);/g, function() {
    return String.fromCharCode(arguments[1]);
    });

    Answered on January 26, 2019.
    Add Comment


  • Your Answer

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