服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - 如何检测 JavaScript 字符串中的 URL 并将其转换为链接?

如何检测 JavaScript 字符串中的 URL 并将其转换为链接?

2021-08-26 23:28杭州程序员小张 JavaScript

有时,我们必须在 JavaScript 字符串中查找 URL。在本文中,我们将了解如何在 JavaScript 字符串中查找 URL 并将它们转换为链接。

有时,我们必须在 JavaScript 字符串中查找 URL。

在本文中,我们将了解如何在 JavaScript 字符串中查找 URL 并将它们转换为链接。

我们可以创建自己的函数,使用正则表达式来查找 URL。

如何检测 JavaScript 字符串中的 URL 并将其转换为链接?

例如,我们可以这样写:

  1. const urlify = (text) => { 
  2.   const urlRegex = /(https?:\/\/[^\s]+)/g; 
  3.   return text.replace(urlRegex, (url) => { 
  4.     return `<a href="${url}>${url}</a>`; 
  5.   }) 
  6. const text = 'Find me at http://www.example.com and also at http://stackoverflow.com'
  7. const html = urlify(text); 
  8. console.log(html) 

我们创建了接受 text 字符串的 urlify 函数。

在函数中,我们优化了 urlRegex 变量,该变量具有用于匹配url的regex。

我们检查 http 或 https 。

然后我们查找斜杠和文本。

正则表达式末尾的 g 标志让我们可以搜索字符串中的所有 URL。

然后我们用 urlRegex 调用 text.replace 并在回调中返回一个带有匹配 url 的字符串。

因此,当我们用 text 调用 urlify 时,我们得到:

  1. '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 搜索更精确。

例如,我们可以这样写:

  1. const urlify = (text) => { 
  2.   const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; 
  3.   return text.replace(urlRegex, (url) => { 
  4.     return `<a href="${url}>${url}</a>`; 
  5.   }) 
  6. const text = 'Find me at http://www.example.com and also at http://stackoverflow.com'
  7. const html = urlify(text); 
  8. console.log(html) 

我们搜索 http、https、ftp 和文件url。

我们还在模式中包含 : 、字母、与号和下划线。

原文链接:https://www.toutiao.com/a6998801586491507233/

延伸 · 阅读

精彩推荐