url - Comment puis-je obtenir des valeurs de chaîne de requêtes en JavaScript

Mots clés : javascripturlpluginsquery-stringjavascript

meilleur 5 Réponses url - Comment puis-je obtenir des valeurs de chaîne de requêtes en JavaScript

vote vote

97

const urlSearchParams = new URLSearchParams(window.location.search); const params = Object.fromEntries(urlSearchParams.entries()); 
const urlParams = new URLSearchParams(window.location.search); const myParam = urlParams.get('myParam'); 
function getParameterByName(name, url = window.location.href) {     name = name.replace(/[\[\]]/g, '\\$&');     var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),         results = regex.exec(url);     if (!results) return null;     if (!results[2]) return '';     return decodeURIComponent(results[2].replace(/\+/g, ' ')); } 
// query string: ?foo=lorem&bar=&baz var foo = getParameterByName('foo'); // "lorem" var bar = getParameterByName('bar'); // "" (present with empty value) var baz = getParameterByName('baz'); // "" (present with no value) var qux = getParameterByName('qux'); // null (absent) 
vote vote

87

var urlParams; (window.onpopstate = function () {     var match,         pl     = /\+/g,  // Regex for replacing addition symbol with a space         search = /([^&=]+)=?([^&]*)/g,         decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },         query  = window.location.search.substring(1);        urlParams = {};     while (match = search.exec(query))        urlParams[decode(match[1])] = decode(match[2]); })();
 urlParams = {     enc: " Hello ",     i: "main",     mode: "front",     sid: "de8d49b78a85a322c4155015fdce22c4",     empty: "" }  alert(urlParams["mode"]); // -> "front"  alert("empty" in urlParams); // -> true 
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
myparam = ["1", "2"] 
let urlParams = {}; (window.onpopstate = function () {     let match,         pl = /\+/g,  // Regex for replacing addition symbol with a space         search = /([^&=]+)=?([^&]*)/g,         decode = function (s) {             return decodeURIComponent(s.replace(pl, " "));         },         query = window.location.search.substring(1);      while (match = search.exec(query)) {         if (decode(match[1]) in urlParams) {             if (!Array.isArray(urlParams[decode(match[1])])) {                 urlParams[decode(match[1])] = [urlParams[decode(match[1])]];             }             urlParams[decode(match[1])].push(decode(match[2]));         } else {             urlParams[decode(match[1])] = decode(match[2]);         }     } })(); 
vote vote

73

getQueryStringParams = query => {     return query         ? (/^[?#]/.test(query) ? query.slice(1) : query)             .split('&')             .reduce((params, param) => {                     let [key, value] = param.split('=');                     params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';                     return params;                 }, {}             )         : {} }; 
var qs = (function(a) {     if (a == "") return {};     var b = {};     for (var i = 0; i < a.length; ++i)     {         var p=a[i].split('=', 2);         if (p.length == 1)             b[p[0]] = "";         else             b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));     }     return b; })(window.location.search.substr(1).split('&')); 
qs["topic"];    // 123 qs["name"];     // query string qs["nothere"];  // undefined (object) 
function (b) {     var c = typeof b === "undefined";     if (a !== h && c) return a;     for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {         var l = b[f][p]("=");         if (l !== -1) {             var q = b[f][I](0, l),                 l = b[f][I](l + 1),                 l = l[Ca](/\+/g, " ");             try {                 d[q] = e(l)             } catch (A) {}         }     }     c && (a = d);     return d } 
(function($) {     $.QueryString = (function(paramsArray) {         let params = {};          for (let i = 0; i < paramsArray.length; ++i)         {             let param = paramsArray[i]                 .split('=', 2);                          if (param.length !== 2)                 continue;                          params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));         }                      return params;     })(window.location.search.substr(1).split('&')) })(jQuery); 
//Get a param $.QueryString.param //-or- $.QueryString["param"] //This outputs something like... //"val"  //Get all params as object $.QueryString //This outputs something like... //Object { param: "val", param2: "val" }  //Set a param (only in the $.QueryString object, doesn't affect the browser's querystring) $.QueryString.param = "newvalue" //This doesn't output anything, it just updates the $.QueryString object  //Convert object into string suitable for url a querystring (Requires jQuery) $.param($.QueryString) //This outputs something like... //"param=newvalue&param2=val"  //Update the url/querystring in the browser's location bar with the $.QueryString object history.replaceState({}, '', "?" + $.param($.QueryString)); //-or- history.pushState({}, '', "?" + $.param($.QueryString)); 
var qs = window.GetQueryString(query);  var search = qs["q"]; var value = qs["value"]; var undef = qs["undefinedstring"]; 
var search = window.getParameterByName("q"); var value = window.getParameterByName("value"); var undef = window.getParameterByName("undefinedstring"); 
vote vote

65

function getParameterByName(name) {     var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);     return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); } 
vote vote

56

const params = new URLSearchParams(location.search); 
const params = (new URL(location)).searchParams; 
const url = new URL('https://example.com?foo=1&bar=2'); const params = new URLSearchParams(url.search); 
const params = new URL('https://example.com?foo=1&bar=2').searchParams; params.get('foo'); // "1" params.get('bar'); // "2"  

Questions similaires