Search code examples
javascriptjqueryregextagging

Regex to find strings that start with # and up until whitespace


I am trying to get any strings in an element that start with # to get a dummy tag system going. basically

#hello #goodbye #good afternoon

Would then show up as

hello goodbye good

This is the regex I have so far

/#^\s/

I'm not very good at regex, though I believe ^\s is what I want to get the text until whitespace.

Example HTML:

<div class="content">
 <div>Hello everyone today we are going to be discussing #world_views , <br />
  Please enjoy today's discussing by #user2
  </div>
</div>

What I want it to turn into is

<div class="content">
 <div>Hello everyone today we are going to be discussing 
    <a href="/search&keywords=world%20views">#world_views</a> , <br />
  Please enjoy today's discussing by <a href="/search&keywords=user2>#user2</a>
  </div>
</div>

Full JavaScript so far:

$(function() {
   var i,forum={
     phpbb2:'.postbody',
     phpbb3:'.post .content',
     punbb:'.entry-content',
     invision:'.postbody'
    },
  yourVersion="phpbb3";

 for (i=0;i<forum[yourVersion].length;i++){
     $(forum[yourVersion][i]).html(function() {
     return $(this)
             .html()
             .replace(
                 /#^\s/,
                '<a href="/search&keywords='+$1.replace("#","")+'">$1</a>');
    });
   }
 });

Solution

  • In JavaScript you create a new RegExp object and then test it.

    Something like this should work.

    var string = $("#some_id").val();
    var regexp = new RegExp("/#^\S+/");
    
    if (regexp.test(string) === true) {
         // do something here
         return true; // optional
    }
    else {
         // do something else here
         return false; // optional
    }