簡體   English   中英

使用Javascript或Lodash替換字符串

[英]Use Javascript or Lodash to replace string

有一種情況,我有一個帶有多個鏈接字符串的字符串,如下所示。 我需要將鏈接替換為實際鏈接,例如: <a href=”http://www.testing.com” target=_blank>http://www.asdfasd.com</a>

示例文字:

http://www.testing.com Simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap https://asdfasdf.com

我正在使用下面的函數來獲取出現'http'的每個地方的索引,但是想知道是否有更簡單的方法。

indexes(comments.Answers, "http");

function indexes(source, find) {
  var result = [];
  for (var i = 0; i < source.length; ++i) {
    // If you want to search case insensitive use 
    // if (source.substring(i, i + find.length).toLowerCase() == find) {
    if (source.substring(i, i + find.length) == find) {
      result.push(i);
    }
  }
 console.log("result ", result);

  return result;
}

不要發布自己的正則表達式,這是錯誤的。 直到為時已晚,您甚至都不會意識到這是錯誤的。 您將花費數小時和幾天的時間仔細研究正則表達式,最后使其正常工作,出去喝醉,辛苦了一段時間,僅讓您的客戶一個月后回來,因為您錯過了一些極端情況而生氣,使所有這些無效您的工作,並迫使您從頭開始。 只是不要去那里。

使用久經考驗的庫。

插件linkify是專門為您的目的而構建的。 他們在頁面上有一個測試框,您可以在其中進行嘗試,它似乎可以完美地處理示例文本。

如果你真的想手動生成的鏈接,圖書館validator.js有一個稱為函數isURL用來檢查是否一個給定的字符串是一個URL。 您可以遍歷用空格分隔的文本單詞,並檢查每個單詞是否都是URL,並根據需要使其成為鏈接。

如果您想探索更多選項,建議您閱讀對此舊帖子的回復。

暫無
暫無

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

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