我在 SO 上查看了其他几个可能的解决方案,但没有看到任何解决方案正在做我正在做的事情。
目前我已经能够使用以下代码解析字符串并检测哈希标签:
mystring = mystring.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, "$1<span class='hash_tag'>$2</span>").replace(/\s*$/, "");
这成功地检测了各种#hashtags。但是,它还会检测 URL 中的 anchor ,例如:http://www.example.com/#anchor - 我不知道如何修改我必须排除 anchor 同时保持灵 active 的内容。
谢谢
最佳答案
这是一个正则表达式来匹配 hashtag(#) 如果它前面有一个空格或者它是字符串的开头......就像这样:
(^|\s)(#[a-z\d-]+)
工作正则表达式示例:
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 中的 anchor 除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421526/