获取URI的路径部分

Kan*_*ali 0 javascript regex

我怎样才能匹配/sk/en,并/fg/tr从这些网址吗?

http://example.com/sk/en
http://example.com/fg/tr
Run Code Online (Sandbox Code Playgroud)

网址可以以http://,https://www.,但不必以.在第一个和第二个斜杠之后总是有两个字母,字母是字母的,无论如何都可以调用.

Ben*_*aum 7

无需为此使用正则表达式.

var url = new URL("http://example.com/sk/en");
console.log(url.pathname); // logs /sk/en
Run Code Online (Sandbox Code Playgroud)

这将适用于http和https,但是如果您需要支持没有协议的URL(顺便说一句,无效的URL),只需将http添加到它们之前.

或者,如果您需要支持旧版浏览器,则可以始终使用DOM:

var a = document.createElement("a"); // create a link element
a.href = "http://example.com/sk/en";
console.log(a.pathname); // /sk/en
Run Code Online (Sandbox Code Playgroud)

URLAPI相当新,因此需要IE10 +和相对较新的Chrome/Firefox才能运行.

createElement方法也适用于旧版本的IE,因此如果您需要支持旧版浏览器 - 请更喜欢它.


你在评论中提到你需要路径后面的前两位,一旦我们有路径名,我们就可以拆分它.假设我们有可以使用的路径变量indexOf并将其与0进行比较

var path = "/ab/cd/ef/gh?foo=bar";
console.log(path.indexOf("/ab/cd") === 0); // true, since /ab/cd is exists in the path
                                           // and its start position is 0
console.log(path.indexOf("/cd/ef")); // 3 and not 0, since it's not at the first position
console.log(path.indexOf("/en/us")); // -1, not found at all.
Run Code Online (Sandbox Code Playgroud)

  • URL类很有用,以前从未了解过它! (3认同)
  • 哇!我从来不知道这些事情.谢谢. (2认同)