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