JavaScript正则表达式用于URL检测和拆分
P粉043432210
P粉043432210 2023-09-21 18:00:47
0
1
584

我有以下URL:

https://comanage.example.edu/sp
https://wiki.cs.example.org/sp
https://intranet.math.example.edu/sp
https://myapp.example.com/sp

对于这些URL,我需要定义一个函数来检测它们是否为URL,并从中替换掉https://和sp路径。基本上,我只需要主机名。例如,如下所示:

https://comanage.example.edu/sp      ->comanage.example.edu
https://wiki.cs.example.org/sp       ->wiki.cs.example.org
https://intranet.math.example.edu/sp ->intranet.math.example.edu
https://myapp.example.com/sp         ->myapp.example.com

对于非URL,该函数应该检测并不进行替换。如下所示:

nonurl.example.com -> ***no replacement***

请问有人能为我提供上述问题的解决方案吗?我对正则表达式的使用知识不多。

P粉043432210
P粉043432210

全部回复(1)
P粉680087550

模式 ^https?:\/\/ 在这里应该很容易使用。我们可以用它来替换任何字符串开头的 http://https:// 为空字符串

在模式中,^ 符号表示字符串的开头。这意味着如果 http:// 在字符串中间出现,它将不会匹配,因为它必须在开头

? 将前一个字符标记为可选。在模式中,s 是可选的,以便找到 httphttps

\/ 是必需的,因为斜杠必须进行转义

const urls = [
  'https://comanage.example.edu/sp',
  'https://wiki.cs.example.org/sp',
  'https://intranet.math.example.edu/sp',
  'https://myapp.example.com/sp',
  'nonurl.example.com',
];

const pattern = /^https?:\/\//i;

urls.forEach(u => {
  console.log(u, '-->', u.replace(pattern, ''));
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!