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

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

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

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

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

[[419576]]

例如,我们可以这样写:

  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。

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

 

责任编辑:赵宁宁 来源: 今日头条
相关推荐

2021-12-29 16:40:54

Python语言字符串

2024-02-19 15:38:08

JsonPython字符串

2009-06-05 11:16:58

字符串动态转换

2022-09-22 11:40:11

JavaScript数组开发

2024-03-12 07:35:39

Python字符串列表

2009-12-01 14:00:37

PHP字符串转换为数值

2024-01-04 09:17:03

前端开发CSV 格式JSON 字符串

2022-12-15 16:23:32

JavaScrip字符串开发

2011-07-11 16:00:22

字符串拼接

2020-09-03 10:13:49

JavaScript字符串pad

2009-11-25 16:55:45

PHP函数explod

2015-06-09 14:43:36

javascript操作字符串

2016-12-30 13:16:51

字符串算法代码

2010-11-26 14:09:32

MySQL内置函数

2021-04-28 09:26:31

Angular 12Ivy开发者

2021-03-26 08:36:35

JavaScript字符串开发

2019-12-25 15:41:50

JavaScript程序员编程语言

2020-10-16 18:35:53

JavaScript字符串正则表达式

2021-11-29 00:17:41

JS符串转换

2021-03-11 18:44:39

字符串SQL表达式
点赞
收藏

51CTO技术栈公众号