JSFiddle - React, Tailwind, and code Playground
getting URL parameters
by jonchius
HTML
<h1></h1>
JavaScript
// getting parameter "id" in URL e.g. http://www.website.com/index.html?user=jon&id=t902a
$("h1").append(getURLParam("id"));
// getting parameter "user"
$("h1").append(" " + getURLParam("user"));
function getURLParam(pKey){
var pValue = "";
// simulate URL for fiddle
// in production, use: var url = window.location.href;
var url = "http://www.website.com/index.html?user=jon&id=t90f2a";
// does the URL have a ? (i.e. does it have parameters?)
if ( url.indexOf("?") > -1 ) {
// if so, take the part of the URL to the right of the ?
var pString = url.substr(url.indexOf("?"));
// split that part using & as a separator into an array
var pArray = pString.split("&");
// look through that array
for ( var i = 0; i < pArray.length; i++ ) {
// look for the strParamName in the array
if ( pArray[i].indexOf(pKey + "=") > -1 ){
// split pKey and pValue
var pPair = pArray[i].split("=");
// take pValue
pValue = pPair[1];
// exit loop
break;
}
}
}
// return the parameter's value
return pValue;
}