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

后端 未结 3 972
我寻月下人不归
我寻月下人不归 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:01

    Here's a regex to match hashtag(#) if it has a space before it or it's beginning of string.. like so:

    (^|\s)(#[a-z\d-]+)
    

    Working regex example:

    http://regex101.com/r/pJ4wC5

    Javascript:

    var string = '#hello This is an #example of some text with #hash-tags - http://www.example.com/#anchor but dont want the link';
    
    string = string.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hash_tag'>$2</span>");
    
    console.log(string);
    

    Output:

    <span class='hash_tag'>#hello</span> This is an <span class='hash_tag'>#example</span> of some text with <span class='hash_tag'>#hash-tags</span> - http://www.example.com/#anchor but dont want the link
    
    0 讨论(0)
  • 2020-12-14 04:08

    I know this has been answered, but if you need styling, here's a solution i used on a project:

    <div id='result'>The quick brown #fox jumps over the #second  lazy dog</div>
    <div id='result2'> </div>
    
    //jquery
    var str = $('#result').html(); 
    var edt = str.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hash_tag'>$2</span>");
    
    $('#result2').html(edt);
    
    
    
    
    //CSS
    .hash_tag {color:red;}
    #result {display:none;}
    
    0 讨论(0)
  • 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 = '<a href="sdfsdfd#ank"> qsdqd</a> #toto (#titi) ^#t-_-Ata';
    
    var result = str.replace(/<a\b[^>]*>|\B(#[^\W_][\w-]*)/gi,
                             function (m, p) {
                              return (p) ? '<span class="hash_tag">'+m+'</span>' : m;
                             });
    
    console.log(result);
    
    0 讨论(0)
提交回复
热议问题