簡體   English   中英

在JavaScript中,將標簽轉換為鏈接的最有效方法是什么?

[英]In javascript, what's the most efficient way to I turn tags into links?

假設我有一些HTML:

Hello, I'm a #robot and this is my #home.

如何將其轉換為:

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>

我嘗試通過遍歷每個單詞並執行查找/替換來使用JQuery,但這非常昂貴。 有什么更好的方法呢?

以下是可用於用鏈接替換井號的代碼。 隨意嘗試一下,並評論您可能有的任何問題:)

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不適用於純文本操作。 我猜這里最好的替代方法是在服務器端進行此類更改。 如果不可能的話,可以通過簡單的查找/替換來解決問題,在這種情況下,可以使用jQuery來迭代包含此HTML的某些元素,從而使訪問更加容易。

高溫超導

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM