javascript - 使用 node.js 中的正则表达式提取字符串的部分
问题描述
例如,我尝试提取唯一 URL 部分而不是路径
如果网址是https://example.com/news/cricket
输出应该是https://example.com/
但我不擅长正则表达式。
data = "https://example.com/news/cricket";
var name = data.substring(0, data.lastIndexOf("/"));
console.log(name);
这是我尝试过的,但输出是:-
https://example.com/news
预期输出为
https://example.com/
谢谢各位医治
解决方案
lastIndexOf()
返回最后一个的索引/
,它是之前的cricked
,而不是之前的news
。
indexOf()
带一个可选的起始索引,你可以先搜索,//
然后再搜索下一个/
。
您需要将 2 添加到索引//
以跳过它。并且您必须将 1 添加到索引中,/
以便将 包含/
在结果中。
data = "https://example.com/news/cricket";
var name = data.substring(0, data.indexOf("/", data.indexOf("//")+2)+1);
console.log(name);
使用正则表达式,使用匹配到第一个//
然后到下一个的正则表达式/
。
var data = "https://example.com/news/cricket";
var match = data.match(/^.*?\/\/.*?\//);
if (match) {
var name = match[0];
console.log(name);
}
推荐阅读
- php - 我想在循环内做一个乘法,但值没有增加
- indexing - 具有单列索引的多维范围查询
- c++ - Eigen 中的多线程(未使用 OpenMP)
- c - signal_connect 函数中的指针工作不正确
- reporting-services - SSRS Reportviewer 工具栏(打印按钮、下一步按钮等)不显示颜色且不成一行
- ios - iOS App 不提示启用通知
- sql - SQL:一次插入多行
- python - 如何在 Python 中搜索以 X 开头的文件?
- firebase - 将文件从 Firebase 存储下载到颤振
- python - 如何在 AWS beanstalk 上使用 Django-background-tasks 部署 Django 应用程序?