How to use javascript to replace hash tags with links from jquery data attribute

I am trying to do the same thing as in this question Change the #hash tag for a link to a page load But I think because I get a string from the data-caption attribute of jquery objects, something is working incorrectly. I have a DOM element like this

<a class="thumbnail" rel="gallery" data-caption="#drink from somewhere #fun" data-pid="36" href="http://domain.com/something"><img src="http://domain.com/somephoto.png" alt="acee7bd0d8339b9ddcf4a259ec7ddeec"></a> 

Basically this is a thumbnail loaded into a modal, then I try to grab the attribute header and create links from any hash tags

  var caption = anchor.attr('data-caption') ? anchor.attr('data-caption') : null; console.log(caption); 

where variable binding is a jquery object representing a link

I see that there is an inscription if I check the journal that it prints "#drink from somewhere #fun"

So now, throwing this into the regex, replace fn

 caption.replace(/#(\S*)/g,'<a href="http://twitter.com/#!/search/$1">$1</a>'); 

Then add a title to the active link DOM.

But nothing happens with the title bar. I just get the same thing as me.

** CHANGE ANSWER silly mistake forgot to assign return value to variable

 var captionLinks = caption.replace(/#(\S*)/g,'<a href="http://twitter.com/#!/search/$1">$1</a>'); 
+7
source share
2 answers

If the code in your question is placed exactly as you use it, you need to assign the result to caption.replace() . Just calling .replace() will not change caption .

Assuming you do this:

 caption.replace(/#(\S*)/g,'<a href="http://twitter.com/#!/search/$1">$1</a>'); 

Try using it as follows:

 caption = caption.replace(/#(\S*)/g,'<a href="http://twitter.com/#!/search/$1">$1</a>'); 

Like the documentation for Replace :

Returns a new line with some or all pattern matches that are replaced with a replacement. A template can be a string or RegExp, and a replacement can be a string or a function that must be called for each match.

Of course, if you already did this, and you just did not publish it, and the problem was something else.

Let me know if this is the case and I will delete my answer as it obviously does not apply.

+12
source

I would go for /#(\S+)/g to avoid a single #

0
source

All Articles