首页 > 解决方案 > 使用 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/

谢谢各位医治

标签: javascriptnode.jsregexpattern-matching

解决方案


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);
}


推荐阅读