-1
var theText='Ohhhh #ohhh #oh #ohh #ohhhh ohhh oh'

what I want to achieve is for each "oh" with a pound/hashtag would be replaced with a link.

What I want to achieve:

"Ohhh <a href='/'>#ohhh</a>
      <a href='/'>#oh</a>
      <a href='/'>#ohh</a>
      <a href='/'>#ohhhh</a>
      ohhh oh
hex494D49
  • 9,109
  • 3
  • 38
  • 47
o2kevin
  • 707
  • 1
  • 5
  • 20

2 Answers2

1

Try the snippet below

var s = "Ohhhh #ohhh #oh #ohh #ohhhh ohhh oh";
var p = /(#[^\s]+)/g;
s.replace(p, "<a href='/'>$1</a>");

Output:

"Ohhhh <a href='/'>#ohhh</a> <a href='/'>#oh</a> <a href='/'>#ohh</a> <a href='/'>#ohhhh</a> ohhh oh"

Demo

hex494D49
  • 9,109
  • 3
  • 38
  • 47
0

I got something using map native function like bellow.

var theText='Ohhhh #ohhh #oh #ohh #ohhhh ohhh oh';
var words = theText.split(' ');
var newWords = words.map(function(part){
        if(part.indexOf('#')==0)
            return "<a href='/'>"+part+"</a>\n";  //\n is because you want line breaks in those words
        else
            return part+" ";
});

var newText = newWords.join('');
console.log(newText);

DEMO

If you want to use it in HTML you can use <br> at the place of \n.

NOTE:- map doesn't work on IE8 there you have to use some libraries.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68