JSFiddle - React, Tailwind, and code Playground
by jfriend00
CSS
body {font-family: "Courier New"; font-size: 13px;}
JavaScript
var tests = [
"http://example.com/whatever#page?x=1&locale=hu&y=2",
"http://example.com/whatever#page?x=1&locale=hu",
"http://example.com/whatever#page?locale=hu",
"http://example.com/whatever#page?locale=",
"http://example.com/whatever#page?x=1",
"http://example.com/whatever#page",
"http://example.com/whatever",
// other test cases I added
"http://example.com/whatever#page?xlocale=foo&x=1&locale=hu&y=2",
"http://example.com/whatever?locale=nomatch#page?x=1&locale=hu&y=2",
"http://example.com/locale/whatever?locale=nomatch#page?x=1&locale=hu&y=2"
];
function getParmsFromURLHash(url) {
var parms = {}, pieces, parts, i;
var hash = url.lastIndexOf("#");
if (hash !== -1) {
// isolate just the hash value
url = url.slice(hash + 1);
}
var question = url.indexOf("?");
if (question !== -1) {
url = url.slice(question + 1);
pieces = url.split("&");
for (i = 0; i < pieces.length; i++) {
parts = pieces[i].split("=");
if (parts.length < 2) {
parts.push("");
}
parms[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
}
return parms;
}
var results = [];
var parms, item;
for (var i = 0; i < tests.length; i++) {
parms = getParmsFromURLHash(tests[i]);
item = parms["locale"] || "";
results.push('"' + item + '"');
}
document.body.innerHTML = results.join("<br>");