使用正则表达式链接单词

时间:2014-09-03 14:48:25

标签: javascript regex hashtag linkify

我正在尝试使用正则表达式链接主题标签,大多数情况都有效,除非最后有一个带有点的单词hot.,这应该只链接#hot,但同时#hot.hot有效

这是我的正则表达式代码:

var text = "#hot#hot hot #hot #hot.hot #hót #hot_hot #hot, (#hot) #hot. hot";
text.replace(#([^\b#,() ]*)/g, '<a href="/$1">#$1</a>');

输出:

<a href="/hot">#hot</a><a href="/hot">#hot</a> hot <a href="/hot">#hot</a> <a href="/hot.hot">#hot.hot</a> <a href="/hót">#hót</a> <a href="/hot_hot">#hot_hot</a> <a href="/hot">#hot</a>, (<a href="/hot">#hot</a>) <a href="/hot.">#hot.</a> hot

唯一的问题是#hot.应该#hot同时仅#hot.hot有效链接

2 个答案:

答案 0 :(得分:3)

你的正则表达式很好,但你必须在最后添加一个单词边界:

#([^\b#,() ]*)\b
              ^-------- Here

<强> Working demo

enter image description here

答案 1 :(得分:0)

尝试使用此正则表达式:

/#([^\W]+)/g

\w仅匹配字母,数字和下划线。因此,它的反面\W匹配字母,数字或下划线的所有内容。将\W置于否定的字符类([^\W])中,您将获得所需的结果,该结果仍然可以与重音字符匹配。