Javascript/jQuery - parse hashtags in a string using regex, except for anchors in URLs

后端 未结 3 976
我寻月下人不归
我寻月下人不归 2020-12-14 03:32

I\'ve looked at a couple of other possible solutions on SO but didn\'t see any that were doing what I was doing.

Currently I have been able to parse a string and det

3条回答
  •  粉色の甜心
    2020-12-14 04:10

    The idea is to try to match the "a" tag first and after trying the hashtag subpattern that is in a capturing group. A callback function tests the capturing group and returns the "a" tag or the modifier hashtag substring:

    var str = ' qsdqd #toto (#titi) ^#t-_-Ata';
    
    var result = str.replace(/]*>|\B(#[^\W_][\w-]*)/gi,
                             function (m, p) {
                              return (p) ? ''+m+'' : m;
                             });
    
    console.log(result);
    

提交回复
热议问题