简体   繁体   English

Javascript / jQuery - 使用正则表达式解析字符串中的主题标签,但URL中的锚点除外

[英]Javascript/jQuery - parse hashtags in a string using regex, except for anchors in URLs

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, "$1<span class='hash_tag'>$2</span>").replace(/\s*$/, "");

And this successfully detects all sorts of #hashtags. 这成功地检测到各种#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. 但是它也会检测URL中的锚点,例如: http//www.example.com/#anchor - 我无法弄清楚如何在保持灵活性的同时修改我必须排除的锚点。

Thanks 谢谢

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: 工作正则表达式示例:

http://regex101.com/r/pJ4wC5 http://regex101.com/r/pJ4wC5

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);

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

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, "$1<span class='hash_tag'>$2</span>");

$('#result2').html(edt);




//CSS
.hash_tag {color:red;}
#result {display:none;}

The idea is to try to match the "a" tag first and after trying the hashtag subpattern that is in a capturing group. 我们的想法是首先尝试匹配“a”标记,然后尝试捕获组中的hashtag子模式。 A callback function tests the capturing group and returns the "a" tag or the modifier hashtag substring: 回调函数测试捕获组并返回“a”标记或修饰符hashtag子字符串:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM