繁体   English   中英

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

[英]Regex to get first word after slash in URL

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

以下是 URL 可能的样子:

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

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

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

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

非正则表达式。

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

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

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

这会给你:

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

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

const path = exp[5];

因此路径后的第一个词使用:

const rootPath = path.split('/')[1];

尝试:

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

我的正则表达式很糟糕,所以我会即兴创作一个效率较低的解决方案: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

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

var urlPath = window.location.pathname.split("/");
if (urlPath.length > 1) {
  var first_part = urlPath[1];
  alert(first_part); 
}
$url = 'http://mysite.com/section/subsection';

$path = parse_url($url, PHP_URL_PATH);

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

$first_part = $components[0];

如果您想获取第一个正斜杠(包括)之后的内容,您可以这样做:

const linkUrl = pathname.replace(/^(.*\/)/, '$1')

比如http://localhost:3000/dashboard/dataExploration将返回/dashboard/dataExploration

请注意,这将帮助您根据 react 应用程序中的位置路径名更改活动链接元素,例如 :)。

string.split('://')[1].split('/')[1];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM