상세 컨텐츠

본문 제목

How to get URL parameter?

Code Snippets/Javascript

by w3labkr 2021. 12. 9. 07:58

본문

HASH

This is what one would use if one uses hashes instead of GET-query delimiter (questionmark):

var params={};window.location.hash.replace(/[#&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k] = v});

getSearchParams

As one line

var params={};window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v});

As a function

function getSearchParams(k) {
  var p = {};
  window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (s, k, v) {
    p[k] = v;
  });
  return k ? p[k] : p;
}

Which you could use as:

getSearchParams()  //returns {key1:val1,key2:val2}
getSearchParams("key1")  //returns val1

setSearchParams

function setSearchParams(obj) {
  var arr = [];
  for (var key in obj) {
    var str = obj[key];
    var num = str * 1;
    if (isNaN(num)) {
      !!str && arr.push(key + '=' + str);
    } else {
      !!num && arr.push(key + '=' + num);
    }
  }
  return arr.length > 0 ? '?' + arr.join('&') : '';
}

Using map function

$.map(params, function (v, i) { return i + '=' + v; }).join('&');

Which you could use as:

var params = getSearchParams();
params.abc = '';
setSearchParams(params);

How to get URL parameter using jQuery or plain JavaScript?

 

How to get URL parameter using jQuery or plain JavaScript?

I have seen lots of jQuery examples where parameter size and name are unknown. My URL is only going to ever have 1 string: http://example.com?sent=yes I just want to detect: Does sent exist? Is...

stackoverflow.com

 

'Code Snippets > Javascript' 카테고리의 다른 글

How to get date using momentjs?  (0) 2021.12.09

관련글 더보기