JavaScript字符串中URL的检测并转换为链接
2021/9/3 9:05:49
本文主要是介绍JavaScript字符串中URL的检测并转换为链接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
有时,我们必须在 JavaScript 字符串中查找 URL。 |
在本文中,我们将了解如何在 JavaScript 字符串中查找 URL 并将它们转换为链接。
我们可以创建自己的函数,使用正则表达式来查找 URL。
例如,我们可以这样写:
const urlify = (text) => { const urlRegex = /(https?:\/\/[^\s]+)/g; return text.replace(urlRegex, (url) => { return `<a href="${url}>${url}</a>`; }) } const text = 'Find me at http://www.example.com and also at http://stackoverflow.com'; const html = urlify(text); console.log(html)
我们创建了接受 text 字符串的 urlify 函数。
在函数中,我们优化了 urlRegex 变量,该变量具有用于匹配url的regex。
我们检查 http 或 https 。
然后我们查找斜杠和文本。
正则表达式末尾的 g 标志让我们可以搜索字符串中的所有 URL。
然后我们用 urlRegex 调用 text.replace 并在回调中返回一个带有匹配 url 的字符串。
因此,当我们用 text 调用 urlify 时,我们得到:
'Find me at <a href="http://www.example.com>http://www.example.com</a> and also at <a href="http://stackoverflow.com>http://stackoverflow.com</a>'
我们可以使用更复杂的正则表达式使 URL 搜索更精确。
例如,我们可以这样写:
const urlify = (text) => { const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; return text.replace(urlRegex, (url) => { return `<a href="${url}>${url}</a>`; }) } const text = 'Find me at http://www.example.com and also at http://stackoverflow.com'; const html = urlify(text); console.log(html)
我们搜索 http、https、ftp 和文件url。
我们还在模式中包含 : 、字母、与号和下划线。
本文地址:https://www.linuxprobe.com/javascript-url-urlregex.html
这篇关于JavaScript字符串中URL的检测并转换为链接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求