Skip to content

Instantly share code, notes, and snippets.

@akiyoshi83
Last active August 29, 2015 14:01
Show Gist options
  • Save akiyoshi83/5f50bb2d7274aab28cf4 to your computer and use it in GitHub Desktop.
Save akiyoshi83/5f50bb2d7274aab28cf4 to your computer and use it in GitHub Desktop.
何度も似たようなの書いてるのでメモ。
// URL RegureExpression.
var regURL = /(https?:)\/\/([^\/]+)(([^?#]*\/)?([^#?]+)?)(\?[^#?]+)?(#.*)?/;
// if matched returns below
// 0: URL ex) "http://example.com/path/to/index.html?foo=bar#baz"
// 1: Scheme ex) "http:"
// 2: Domain ex) "example.com"
// 3: Path ex) "/path/to/index.html"
// 4: Directory ex) "/path/to/"
// 5: File ex) "index.html"
// 6: Query ex) "?foo=bar"
// 7: Hash ex) "#baz"
regURL.exec("http://example.com");
["http://example.com", "http:", "example.com", "", undefined, undefined, undefined, undefined]
regURL.exec("http://example.com/");
["http://example.com/", "http:", "example.com", "/", "/", undefined, undefined, undefined]
regURL.exec("http://example.com/index.html");
["http://example.com/index.html", "http:", "example.com", "/index.html", "/", "index.html", undefined, undefined]
regURL.exec("http://example.com/path/to/index.html");
["http://example.com/path/to/index.html", "http:", "example.com", "/path/to/index.html", "/path/to/", "index.html", undefined, undefined]
regURL.exec("http://example.com/path/to/index.html?foo=bar");
["http://example.com/path/to/index.html?foo=bar", "http:", "example.com", "/path/to/index.html", "/path/to/", "index.html", "?foo=bar", undefined]
regURL.exec("http://example.com/path/to/index.html?foo=bar#baz");
["http://example.com/path/to/index.html?foo=bar#baz", "http:", "example.com", "/path/to/index.html", "/path/to/", "index.html", "?foo=bar", "#baz"]
regURL.exec("http://example.com/?foo=bar");
["http://example.com/?foo=bar", "http:", "example.com", "/", "/", undefined, "?foo=bar", undefined]
regURL.exec("http://example.com/#baz");
["http://example.com/#baz", "http:", "example.com", "/", "/", undefined, undefined, "#baz"]
// 以下のようにauth, port 等にも対応した版
// https://user:pass@example.com:8080/path/to/file.html?foo=bar&#baz
var regURL = /(https?:)\/\/(([^\/@]+)@)?(([^\/:@]+):?(\d+)?)(([^?#]*\/)?([^#?]+)?)(\?[^#?]+)?(#.*)?/;
regURL.exec("https://user:pass@example.com:8080/path/to/file.html?foo=bar&#baz")
["https://user:pass@example.com:8080/path/to/file.html?foo=bar&#baz",
"https:",
"user:pass@",
"user:pass",
"example.com:8080",
"example.com",
"8080",
"/path/to/file.html",
"/path/to/",
"file.html",
"?foo=bar&",
"#baz"]
// TODO test case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment