【问题标题】:Use Javascript or Lodash to replace string使用 Javascript 或 Lodash 替换字符串
【发布时间】:2016-08-10 16:00:14
【问题描述】:

有一种情况,我有一个包含多个链接字符串的字符串,如下所示。我需要用实际链接替换链接,例如:<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;
}

【问题讨论】:

  • 您提供的源文本中没有http 的实例。你能更清楚你想要做什么吗?看起来 RegEx 可能是一个可能的解决方案。
  • 是的,为什么不干脆做str.replace(/www.testing.com/gi, '&lt;a href="$1"&gt;$1&lt;/a&gt;')
  • 我不知道网址是什么。文本由客户端提供,需要自动格式化 URL

标签: javascript string lodash


【解决方案1】:

不要滚动你自己的正则表达式,你会做错的。你甚至不会意识到这是错误的,直到为时已晚。您将花费数小时和数天的时间来研究您的正则表达式并最终使其正常工作,出去喝醉,狂欢一段时间,只是让您的客户在一个月后回来生气,因为您错过了一些边缘情况,使所有内容无效你的工作,并迫使你从头开始。只是不要去那里。

使用久经考验的库。

插件linkify 专为您的目的而构建。他们在页面上有一个测试框,您可以在其中尝试一下,它似乎可以完美地处理您的示例文本。

如果您真的想手动构建链接,validator.js 库有一个名为isURL 的函数,它检查给定字符串是否为 URL。您可以遍历以空格分隔的文本单词并检查每个单词是否为 URL,并根据需要将其设为链接。

如果您想探索更多选项,我建议您阅读对this old post 的回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    相关资源
    最近更新 更多