Javascript / jQuery - 使用正则表达式解析字符串中的主题标签,但URL中的锚点除外 [英] Javascript/jQuery - parse hashtags in a string using regex, except for anchors in URLs
问题描述
我在SO上看了几个其他可能的解决方案,但没有看到我正在做的事情。
I've looked at a couple of other possible solutions on SO but didn't see any that were doing what I was doing.
目前我已经能够使用以下代码解析字符串并检测哈希标记:
Currently I have been able to parse a string and detect hash tags with the following code:
mystring = mystring.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, "$1<span class='hash_tag'>$2</span>").replace(/\s*$/, "");
这成功检测到各种#hashtags。但是,它还会检测URL中的锚点,例如: http://www.example.com/#anchor - 我无法弄清楚如何在保持灵活性的同时修改我的排除锚点。
And this successfully detects all sorts of #hashtags. However it also detects anchors in URLs, such as: http://www.example.com/#anchor - I can't work out how to modify what I have to exclude anchors while keeping it flexible.
谢谢
推荐答案
这是一个匹配hashtag(#)的正则表达式,如果它前面有一个空格或它是字符串的开头..就像这样:
Here's a regex to match hashtag(#) if it has a space before it or it's beginning of string.. like so:
(^|\s)(#[a-z\d-]+)
工作正则表达式示例:
Javascript:
Javascript:
var string = '#hello This is an #example of some text with #hash-tags - http://www.example.com/#anchor but dont want the link';
string = string.replace(/(^|\s)(#[a-z\d-]+)/ig, "$1<span class='hash_tag'>$2</span>");
console.log(string);
输出:
<span class='hash_tag'>#hello</span> This is an <span class='hash_tag'>#example</span> of some text with <span class='hash_tag'>#hash-tags</span> - http://www.example.com/#anchor but dont want the link
这篇关于Javascript / jQuery - 使用正则表达式解析字符串中的主题标签,但URL中的锚点除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!