Javascript/jQuery - 使用正则表达式解析字符串中的主题标签,URL 中的锚点除外
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21421526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/jQuery - parse hashtags in a string using regex, except for anchors in URLs
提问by Martin
I've looked at a couple of other possible solutions on SO but didn't see any that were doing what I was doing.
我在 SO 上查看了其他几个可能的解决方案,但没有看到任何正在做的事情。
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, "<span class='hash_tag'></span>").replace(/\s*$/, "");
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.
这成功地检测到各种#hashtags。但是,它也会检测 URL 中的锚点,例如:http: //www.example.com/#anchor- 我不知道如何在保持灵活性的同时修改我必须排除的锚点。
Thanks
谢谢
回答by Bryan Elliott
Here's a regex to match hashtag(#) if it has a space before it or it's beginning of string.. like so:
这是一个正则表达式来匹配 hashtag(#) 如果它前面有一个空格或者它是字符串的开头......像这样:
(^|\s)(#[a-z\d-]+)
Working regex example:
工作正则表达式示例:
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, "<span class='hash_tag'></span>");
console.log(string);
Output:
输出:
<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
回答by sabatino
I know this has been answered, but if you need styling, here's a solution i used on a project:
我知道这已经得到了回答,但是如果您需要样式,这是我在项目中使用的解决方案:
<div id='result'>The quick brown #fox jumps over the #second lazy dog</div>
<div id='result2'> </div>
//jquery
var str = $('#result').html();
var edt = str.replace(/(^|\s)(#[a-z\d-]+)/ig, "<span class='hash_tag'></span>");
$('#result2').html(edt);
//CSS
.hash_tag {color:red;}
#result {display:none;}
回答by Casimir et Hippolyte
The idea is to try to match the "a" tag first and after trying the hashtag subpattern that is in a capturing group. A callback function tests the capturing group and returns the "a" tag or the modifier hashtag substring:
这个想法是先尝试匹配“a”标签,然后再尝试捕获组中的主题标签子模式。回调函数测试捕获组并返回“a”标签或修饰符主题标签子字符串:
var str = '<a href="sdfsdfd#ank"> qsdqd</a> #toto (#titi) ^#t-_-Ata';
var result = str.replace(/<a\b[^>]*>|\B(#[^\W_][\w-]*)/gi,
function (m, p) {
return (p) ? '<span class="hash_tag">'+m+'</span>' : m;
});
console.log(result);