邮箱转换为html模式,如何使用javascript将URL(网站,电子邮件)从字符串转换为html标签...

本文概述

快速实施

如果你想将文本url快速转换为可点击的链接(在dom或字符串中), 则需要知道这对你自己来说并不是一件容易的事。 URI很复杂, 在数百万种情况下, 你自已实现的功能可能会失败。例如 :

function linkify(inputText) {

var replacedText, replacePattern1, replacePattern2, replacePattern3;

//URLs starting with http://, https://, or ftp://

replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:, .;]*[-A-Z0-9+&@#\/%=~_|])/gim;

replacedText = inputText.replace(replacePattern1, '$1');

//URLs starting with "www." (without // before it, or it'd re-link the ones done above).

replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

replacedText = replacedText.replace(replacePattern2, '$1$2');

//Change email addresses to mailto:: links.

replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2, 6})+)/gim;

replacedText = replacedText.replace(replacePattern3, '$1');

return replacedText;

}

先前的功能可以使用, 但是有更好的方法可以完成此任务。

使用库(Linkify.js)

好吧, 第一点是干净且实用, 但在某些情况下可能会失败。我们建议你使用一个可以为你完成所有工作的库, 而不是让你费神学习如何处理字符串和搜索url。

我们正在谈论Linkify.js。 Linkify是一个JavaScript插件, 用于查找纯文本链接并将其转换为HTML 标签。它适用于所有有效的Web URL和电子邮件地址。要将linkify包含在你的项目中, 请访问主页并下载发行版(或使用npm或bower), 并将脚本包含在文档中:

Linkify提供了多种初始化方法, 使用jQuery可以直接转换链接中的DOM内容, 例如:

Visit ourcodeworld.com , it has a lot of interesting content. You can contact us writing to dev@ourcodeworld.com

$("#linkDemo").linkify({

target:"_blank"

});

应该输出:

访问ourcodeworld.com, 它有很多有趣的内容。你可以写信给dev@ourcodeworld.com与我们联系。

或仅使用没有jQuery的linkify核心(在此处了解有关模式的更多信息):

var str = '

For help with GitHub.com, please email support@github.com

';

var processedContent = linkifyStr(str, options);

// or

// var processedContent = str.linkify();

document.getElementById("linkDemo").innerHTML = processedContent;

你可以在官方主页上测试自己的文本, 玩得开心!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值