简体   繁体   English

使用Javascript或Lodash替换字符串

[英]Use Javascript or Lodash to replace string

Have a situation where I have a string with multiple links strings as below. 有一种情况,我有一个带有多个链接字符串的字符串,如下所示。 I need to replace the link with actual links eg : <a href=”http://www.testing.com” target=_blank>http://www.asdfasd.com</a> 我需要将链接替换为实际链接,例如: <a href=”http://www.testing.com” target=_blank>http://www.asdfasd.com</a>

Example text: 示例文字:

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

I am using the below function to get indexes of everywhere that the 'http' occurs but wanted to know if there is an easier way. 我正在使用下面的函数来获取出现'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;
}

Don't roll your own regex, you'll do it wrong. 不要发布自己的正则表达式,这是错误的。 And you won't even realize it's wrong until it's too late. 直到为时已晚,您甚至都不会意识到这是错误的。 You'll spend hours and days poring over your regex and finally get it working, go out and get drunk, party hard for a while, only for your clients to come back a month later pissed off that you missed some edge case, invalidating all your work and forcing you to start from scratch. 您将花费数小时和几天的时间仔细研究正则表达式,最后使其正常工作,出去喝醉,辛苦了一段时间,仅让您的客户一个月后回来,因为您错过了一些极端情况而生气,使所有这些无效您的工作,并迫使您从头开始。 Just don't go there. 只是不要去那里。

Use a tried-and-tested library. 使用久经考验的库。

The plugin linkify is built specifically for your purpose. 插件linkify是专门为您的目的而构建的。 They have a test box on the page where you can try it out, it seems to handle your example text perfectly. 他们在页面上有一个测试框,您可以在其中进行尝试,它似乎可以完美地处理示例文本。

If you really want to build the links manually, the library validator.js has a function called isURL which checks if a given string is a URL. 如果你真的想手动生成的链接,图书馆validator.js有一个称为函数isURL用来检查是否一个给定的字符串是一个URL。 You can iterate through your whitespace-delimited words of text and check if each is a URL, and make it a link as necessary. 您可以遍历用空格分隔的文本单词,并检查每个单词是否都是URL,并根据需要使其成为链接。

If you want to explore further options I'd recommend reading the replies to this old post . 如果您想探索更多选项,建议您阅读对此旧帖子的回复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM