简体   繁体   English

在JavaScript中,将标签转换为链接的最有效方法是什么?

[英]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.

相关问题 使用JavaScript评估字符串是否是回文符的最有效方法是什么? - What's the most efficient way to evaluate if a string is a palindrome using Javascript? 在Java中通过字符串的最有效方式是什么? - What is the most efficient way to go through string's chars in Javascript? 比较 javascript 中的 2 个元素的最有效方法是什么? - What's the most efficient way to compare 2 elements in javascript? 在Javascript中创建嵌套div的最有效方法是什么? - What is the most efficient way to create nested div's in Javascript? 在 JavaScript 中处理显示对话框/模式的最有效方法是什么? - What's the most efficient way to handle displaying a dialog/modal in JavaScript? 等待Java中异步函数调用的最有效方法是什么? - What's the most efficient way to wait for an asynchronous function call in Javascript? 将 object 的所有键转换为小写的最佳方法(最有效)是什么? - What's the best way (most efficient) to turn all the keys of an object to lower case? 选择具有特定数据的所有html标签的最有效方法是什么?[适当]无论价值如何? - What's the most efficient way of selecting all html tags that have a specific data-[propriety] regardless of value? 在Javascript中声明函数的最有效方法是什么? - What is the most efficient way to declare functions in Javascript? 在Javascript中实现GroupBy的最有效方法是什么? - What is the most efficient way to implement GroupBy in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM