JavaScript - string regex backreferences

后端 未结 5 1687
抹茶落季
抹茶落季 2020-11-27 02:51

You can backreference like this in JavaScript:

var str = \"123 $test 123\";
str = str.replace(/(\\$)([a-z]+)/gi, \"$2\");

This would (quite

5条回答
  •  我在风中等你
    2020-11-27 03:31

    Using ESNext, quite a dummy links replacer but just to show-case how it works :

    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 `${link.substr(link.lastIndexOf('/') +1)}`;
    });
    
    document.body.innerHTML = text;

提交回复
热议问题