In this page it is presented a function that can be used to get search data from URL address in JavaScript, data added after the '?' character.
The function presented bellow receive the URL address, then returns an object with elements "name: value" formed with the "name=value" pairs from that URL.
// Returns an object with elements 'name: value' with data ftom URL (the 'name=value' pairs) function getDataUrl(url) { // https://coursesweb.net/javascript/ var url_data = url.match(/\?([^#]*)/i)[1]; // gets the string between '?' and '#' // separate the data into an array, in case the are multiple pairs name=value var ar_url_data = url_data.split('&'); // traverse the array, and adds into an object elements name:value var data_url = {}; for(var i=0; i<ar_url_data.length; i++) { var ar_val = ar_url_data[i].split('='); // separate name and value from each pair data_url[ar_val[0]] = ar_val[1]; } return data_url; }
<h4>Example getting data from URL query string</h4> <p>Gets and shows the value of 'name' and 'id' from this URL:<br> <b>//marplo.net/?name=Mar&id=10</b></p> <script> // Returns an object with elements 'name: value' with data ftom URL (the 'name=value' pairs) function getDataUrl(url) { // https://coursesweb.net/javascript var url_data = url.match(/\?([^#]*)/i)[1]; // gets the string between '?' and '#' // separate the data into an array, in case the are multiple pairs name=value var ar_url_data = url_data.split('&'); // traverse the array, and adds into an object elements name:value var data_url = {}; for(var i=0; i<ar_url_data.length; i++) { var ar_val = ar_url_data[i].split('='); // separate name and value from each pair data_url[ar_val[0]] = ar_val[1]; } return data_url; } // Using getDataUrl() var url = '//marplo.net/?name=Mar&id=10'; var data_url = getDataUrl(url); // gets the object with 'name:value' data var name = data_url.name; var id = data_url.id; // test document.write('name: '+ name +'<br> id: '+ id); </script>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net