Question

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>');
    });
   }
 });
Was it helpful?

Solution 2

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
}

OTHER TIPS

You're looking for "anything that is not a whitespace character, one or more times" which in regex, looks like:

\S+

So, for your regex, it would be:

/#\S+/

You can also look into using a capturing group that will contain only the text that \S+ matched, like this:

/#(\S+)/

Now capturing group #1 will contain the text of the hashtag, without the hash sign.

The best way to work with regex, is to test them first in a regex-test environment such as 'http://www.solmetra.com/scripts/regex/index.php'.

The above example '/#(\S+)/' will give you the following result: Summary:

  preg_match_all('/#(\S+)/', '#hello #goodbye #good afternoon', $arr, PREG_PATTERN_ORDER);

Function returned

  int(3)

Result set:

Array
(
    [0] => Array
        (
            [0] => #hello
            [1] => #goodbye
            [2] => #good
        )
    [1] => Array
        (
            [0] => hello
            [1] => goodbye
            [2] => good
        )
)

I hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top