[英]Turning text with # symbols into links in javascript
I was wondering how would I do the following using Javascript. 我想知道如何使用Javascript执行以下操作。
Suppose I had a text like the following 假设我有如下文字
var test = '#test is a #cool #place';
and I want the following 我想要以下
<a href="abc.html?q=test">#test</a> is a <a href="abc.html?q=cool">#cool</a> <a href="abc.html?q=place">#place</a>
How would I do that? 我该怎么做?
test = test.replace(/#([^ ]+)/g, '<a href="abc.html?q=$1">#$1</a>');
I personally like this better: 我个人更喜欢这样:
stringToMatch.replace(/(<a[^>]*)?#(\w+)(?!\w)(?!.*?<\/a>)/g,
function($0, $1, $2) {
return $1 ? $0 : '<a href="'+ window.location +'?q=' + $2 + '">#' + $2 + '</a>';
}
));
This will match everything except other links. 这将匹配除其他链接以外的所有内容。 See this example . 请参阅此示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.