簡體   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