本文介绍了JavaScript正则表达式,搜索主题标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一些文本中搜索任何和所有主题标签(字母数字和下划线和连字符)并将它们换成span标签
例如搜索

How can I search some text for any and all hashtags (alphanumeric AND underscore AND hyphen) and wrap them in span tagseg search

some_string = "this is some text with 3 hashtags #Tag1 and #tag-2 and #tag_3 in it"

并将其转换为:

"this is some text with 3 hashtags <span>#Tag1</span> and <span>#tag-2</span> and <span>#tag_3</span> in it"

到目前为止我已经得到了这个:

I've got this so far:

    some_string = some_string.replace(/\(#([a-z0-9\-\_]*)/i,"<span>$1</span>");

但是一个错误是它不包括#应该包装中的#。
似乎输出:

but one fault is it doesn't include the # in the wrappings like it should.It seems to output:

"this is some text with 3 hashtags <span>Tag1</span> and #tag-2 and #tag_3 in it "

此外,它只检测第一个#标签t它遇到的帽子(例如#Tag1 在此示例中),它应该检测全部。

Also it only detects the first hashtag that it comes across (eg. #Tag1 in this sample), it should detect all.

此外,我需要将标签符号设置为最小值#之后的1个字符。所以#本身不应该匹配。

Also I need the hashtags to be a minimum of 1 character AFTER the #. So # on its own should not match.

谢谢

推荐答案

试试这个替换电话:

编辑:如果你想跳过 http://site.com/#tag 然后使用一种字符串:

if you want to skip http://site.com/#tag kind of strings then use:

var repl = some_string.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, '$1<span>$2</span>');

这篇关于JavaScript正则表达式,搜索主题标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:56