1

How to change # tag + Character to link using javascript

This is going #right on the way

with

This is going <a href="http://twitter.com/#!/search/right">right</a> on the way

even this is also acceptable

This is going <a href="http://twitter.com/#!/search/right">#right</a> on the way

The page lots's of # (hash) tag in different classes and id's

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Basic Bridge
  • 1,881
  • 4
  • 25
  • 37

2 Answers2

5
var string = "This is going #right on the way";
string.replace(/#(\S*)/g,'<a href="http://twitter.com/#!/search/$1">$1</a>')

Demo: http://jsfiddle.net/dKm82/

amosrivera
  • 26,114
  • 9
  • 67
  • 76
  • I removed my comment after seeing your demo..!! at first i got confused sorry for that..!! – Basic Bridge Sep 27 '11 at 20:20
  • @Basic Bridge got it, no problem – amosrivera Sep 27 '11 at 20:23
  • here is one little problem it multiply text 2 times.. see this demo http://jsfiddle.net/dKm82/1/ – Basic Bridge Sep 27 '11 at 20:33
  • the problem has to do with the jquery logic, if you want to modify the text of several paragraphs you have to loop over them, see http://jsfiddle.net/dKm82/2/ – amosrivera Sep 27 '11 at 20:37
  • and this is last query what if condition is like this one http://jsfiddle.net/dKm82/3/ this only change first letter not all in the

    tag

    – Basic Bridge Sep 27 '11 at 20:44
  • 1
    @BasicBridge you have a point there, there was a little detail, note that i added "g" to the regular expression, this tells it to repalce multiple times see: http://jsfiddle.net/dKm82/4/ – amosrivera Sep 27 '11 at 20:47
1

here is my suggestion

(function(){

$.fn.hashlink = function(){
  this.text(this.text().replace(\#(w+)\),"<a href='twitter.com/#!/search/$1'>$1</a>")
  text = \#w+\g.
}    

})
bigblind
  • 12,539
  • 14
  • 68
  • 123