Javascript 正则表达式在 URL 中的斜杠后获取第一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5735483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:38:24  来源:igfitidea点击:

Regex to get first word after slash in URL

javascriptregex

提问by dom

I need to get the first word after slash in a url in javascript, I assume using a regex would be ideal.

我需要在 javascript 中的 url 中获取斜杠后的第一个单词,我认为使用正则表达式是理想的。

Here's an idea of what the URLs can possibly look like :

以下是 URL 可能是什么样子的想法:

In bold is what I need the regex to match for each scenario, so basically only the first portion after the slash, no matter how many further slashes there are.

粗体是我需要正则表达式来匹配每个场景的内容,所以基本上只有斜线后面的第一部分,不管有多少进一步的斜线。

I'm at a complete loss here, appreciate the help.

我在这里完全不知所措,感谢您的帮助。

回答by Brandon McKinney

JavaScript with RegEx. This will match anything after the first / until we encounter another /.

带有正则表达式的 JavaScript。这将匹配第一个 / 之后的任何内容,直到我们遇到另一个 /。

window.location.pathname.replace(/^\/([^\/]*).*$/, '');

回答by Alex Emilov

Non-regex.

非正则表达式。

var link = document.location.href.split('/');
alert(link[3]);

回答by Flavien Volken

Exploding an url in javascript can be done using the official rfc2396 regex:

可以使用官方的rfc2396 正则表达式在 javascript 中分解 url :

var url = "http://www.domain.com/path/to/something?query#fragment";
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);

This will gives you:

这会给你:

["", "http:", "http", "//www.domain.com", "www.domain.com", "/path/to/something", "?query", "query", "#fragment", "fragment", ""]

Where you can, in your case, easily retrieve you path with:

在您的情况下,您可以通过以下方式轻松检索路径:

var firstPortion = exp[5].split("/")[1]

回答by hsz

Try with:

尝试:

var url = 'http://mysite.com/section-with-dashes/';
var section = url.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[0];

回答by Fareesh Vijayarangam

My regex is pretty bad, so I will improvise with a less efficient solution :P

我的正则表达式很糟糕,所以我会即兴创作一个效率较低的解决方案:P

// The first part is to ensure you can handle both URLs with the http:// and those without

x = window.location.href.split("http:\/\/")
x = x[x.length-1];
x = x.split("\/")[1]; //Result is in x

回答by Ady Ngom

Here is the quick way to get that in javascript

这是在javascript中获得它的快速方法

var urlPath = window.location.pathname.split("/");
if (urlPath.length > 1) {
  var first_part = urlPath[1];
  alert(first_part); 
}

回答by Marc B

$url = 'http://mysite.com/section/subsection';

$path = parse_url($url, PHP_URL_PATH);

$components = explode('/', $path);

$first_part = $components[0];