[英]In javascript, what's the most efficient way to I turn tags into links?
Let's say I have some HTML: 假设我有一些HTML:
Hello, I'm a #robot and this is my #home.
How can I turn this into: 如何将其转换为:
Hello, I'm a <a href="blah.com/robot" class="tag">#robot</a> and this is my <a href="blah.com/home" class="tag">#home</a>
I've tried using JQuery by iterating over each word and doing a find/replace, but it was very expensive. 我尝试通过遍历每个单词并执行查找/替换来使用JQuery,但这非常昂贵。 What's a better way to do it?
有什么更好的方法呢?
Below is the code you can use to replace hash signs with a link. 以下是可用于用链接替换井号的代码。 Feel free to experiment with it, and comment any questions you may have :)
随意尝试一下,并评论您可能有的任何问题:)
var text = "Hello, I'm a #robot and this is my #home.";
alert(text.replace(/#([a-z0-9]+)/gi, '<a href="blah.com/$1">#$1</a>'));
// It alerts the following "Hello, I'm a <a href="blah.com/robot">#robot</a> and this is my <a href="blah.com/home">#home</a>."
jQuery is not intended for pure text manipulation. jQuery不适用于纯文本操作。 I guess the best alternative here would be do such changes server-side.
我猜这里最好的替代方法是在服务器端进行此类更改。 If not possible, a simple find/replace would do the trick, in such case jQuery could be used just to iterate over some elements that contains this HTML, making its access easier.
如果不可能的话,可以通过简单的查找/替换来解决问题,在这种情况下,可以使用jQuery来迭代包含此HTML的某些元素,从而使访问更加容易。
HTH 高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.