How do I use javascript to replace hash tags with links from a jquery data-attribute

对着背影说爱祢 提交于 2019-12-18 13:29:26

问题


I'm effectively trying to do the same as in this question Change #hash tag to link on page load But I think because I'm getting the string from a jquery objects data-caption attribute something isn't working correctly. 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>

It's basically a thumbnail that is loaded into a modal then i'm trying to grab the attribute caption and create links out of any hash tags

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

where the variable anchor is a jquery object representative of the link

I can see there is a caption if i check the log it prints "#drink from somewhere #fun"

So now throwing that in a regex replace fn

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

Then append the caption to the DOM with the links active.

But nothing happens to the caption string I just get the same thing out that I put in.

**EDIT ANSWER dumb mistake forgot to assign the return value to a variable

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

回答1:


If you code in your question is posted exactly as you use it, you need to assign the result of the caption.replace(). Just calling .replace() won't change caption.

Assuming all you are doing is this:

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

Try using it like this:

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

As per documentation for Replace:

Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Off course, if you already have been doing it and you simply didn't post that than the issue is something else.

Let me know if that is the case and I will remove my answer as it then obviously does not apply.




回答2:


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



来源:https://stackoverflow.com/questions/13655333/how-do-i-use-javascript-to-replace-hash-tags-with-links-from-a-jquery-data-attri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!