Get url parameter with javascript [duplicate] - javascript

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 months ago.
I try to get a URL parameter nr, but I get always false.
var url = window.location.href;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
What is the error?

Use
var url = window.location;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
because window.location is a Location object with a .search property
whereas window.location.href is a string, without a .search property
therefore your url.search is undefined
I can demonstrate with URL which is similar to Location in this respect
let loc = new URL('http://example.com/?nr=1');
// loc is a placeholder for your window.location
let url = loc.href;
// here, url.search would be window.location.href.search
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
console.log(nr);
url = loc;
// here, url.search would be window.location.search
params = new URLSearchParams(url.search);
nr = params.has('nr')
console.log(nr);

The below function will return Array of all parameters from url
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var params = getUrlVars();
console.log(params["nr"]);
reference taken from https://stackoverflow.com/a/20097994/8077687

From https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present.
So you should only provide the query params string.
e.g. if your window.location.href is
https://stackoverflow.com/questions/68314446/get-url-parameter-with-javascript?query=1&query_1=2&many_queries=3
Then you should pass the URLSearchParams class only the query params, viz
query=1&query_1=2&many_queries=3

Related

Parse search params in relative URL in Javascript

I have a relative URL, something like /a/b?someParam=cccc
I want to extract the value of the parameter. One alternative is to do (new URL(myUri, 'http://example.com')).searchParams.get('someParam'). It is nice because it uses the built-in functions from the browser and it is going to be safe in cases when the parameter of the url is encoded.
However, it depends on a random base of the url http://example.com. Is there a way to parse a URL without a base? Or to extract the search params?
You could take everything after the ? and pass it directly to URLSearchParams.
const getParamsFromURI = ( uri ) => {
// Get everything after the `?`
const [ , paramString ] = uri.split( '?' );
// Return parameters
return new URLSearchParams( paramString );
};
const params = getParamsFromURI( '/a/b?someParam=cccc' );
console.log( params.get( 'someParam' ) );
Or if you want to use the URL constructor you can get a base from window.location.origin
const getParamsFromURI = ( uri ) => {
// Create url with base
const base = window.location.origin; // Could also be a fixed value e.g. http://example.com
const url = new URL( uri, base );
// Return parameters
return url.searchParams;
};
const params = getParamsFromURI( '/a/b?someParam=cccc' );
console.log( params.get( 'someParam' ) );
Try this:
const paramString = "/a/b?someParam=cccc".split("?")[1];
const params = new URLSearchParams(paramString);
const result = Object.fromEntries(params.entries());
console.log(result);
You could manipulate the string like this
var test = "/a/b?someParam=cccc&someotherparam=bbb";
var params = test.split('?')[1].split('&').map( (e) => {
let temp = e.split('=');
let rObj = {};
rObj[temp[0]] = temp[1];
return rObj;
} );
console.log(params);
At first you split the string to two segments (before and after "?"). Then you split again the second part by the "&" symbol to generate an array of strings.
In the end you map the array to generate an object with keys and values.
I hope the helps.
EDIT
If you want to use the method URLSearchParams you could do it like this
var test = "/a/b?someParam=cccc&someotherparam=bbb";
var params = new URLSearchParams(test.split('?')[1]);
console.log(params.get("someParam"));
var url_string = "/a/b?someParam=cccc";
function getParam( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
console.log(getParam('someParam', url_string))

How to replace this url to my a format id that i want, thanks [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
Is there any way (maybe a regex) to replace the id dynamic to "id"
I use js and typescript
The original url:
localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728
The url i want:
localhost:4200/reservations/id/properties/id
Here's a solution using regex:
function replaceURL(url, data) {
Object.entries(data).forEach(([key, value]) => url = url.replace(new RegExp(`(?<=${key}\\/)\\w+`, 'g'), value));
return url;
}
// the original url
const url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
// put what you want to replace in this object
const data = {
reservations: 'id',
properties: 'id'
};
const result = replaceURL(url, data);
console.log(result);
Edit
I think I overthought the situation, if you just want to replace the text similar to 5eda023aed43c1e46d6ce804, you can just use the following regex:
/(?<=\/)[0-9a-f]{24,}/g
const regex = /(?<=\/)[0-9a-f]{24,}/g;
let url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
let result = url.replace(regex, 'id');
console.log(result);
url = 'http://localhost:4200/minibar/items/5efdcee02c37c160e8a5bbe1';
result = url.replace(regex, 'id');
console.log(result);
You can try this
let url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
let replacedUrl = url.replace(/\/[a-fA-F0-9]{24}/g, "/id");
console.log(replacedUrl);
If your url format is fix then you can use this simple code.
var link=" localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728";
//var link="http://localhost:4200/minibar/items/5efdcee02c37c160e8a5bbe1"
var hasNumber = /\d/;
var linkParts=link.split("/");
var i=link.indexOf("http")==0?3:2;
for(i;i<linkParts.length;i++)
{
if(linkParts[i].length>20 && hasNumber.test(linkParts[i]))
linkParts[i]="id";
}
document.write(linkParts.join("/"));
You can simply replace the exact id with what you want.
let url = 'localhost:4200/reservations/5eda023aed43c1e46d6ce804/properties/5ca199fdda8ba619695b5728';
let id = '5eda023aed43c1e46d6ce804' // the id to replace
let rx = new RegExp(id,"g"); // use "g" to indicate it should should ALL ids in the string
url = url.replace(rx, "id") // this will replace the dynamic id with the word "id"
// localhost:4200/reservations/id/properties/id

Javascript get URL parameter that starts with a specific string

With javascript, I'd like to return any url parameter(s) that start with Loc- as an array. Is there a regex that would return this, or an option to get all url parameters, then loop through the results?
Example: www.domain.com/?Loc-chicago=test
If two are present in the url, I need to get both, such as:
www.domain.com/?Loc-chicago=test&Loc-seattle=test2
You can use window.location.search to get all parameters after (and including ?) from url. Then it's just a matter of looping through each parameter to check if it match.
Not sure what kind of array you expect for result but here is very rough and basic example to output only matched values in array:
var query = window.location.search.substring(1);
var qsvars = query.split("&");
var matched = qsvars.filter(function(qsvar){return qsvar.substring(0,4) === 'Loc-'});
matched.map(function(match){ return match.split("=")[1]})
Use URLSearchparams
The URLSearchParams interface defines utility methods to work with the
query string of a URL.
var url = new URL("http://" + "www.domain.com/?Loc-chicago=test&NotLoc=test1&Loc-seattle=test2");
var paramsString = url.search;
var searchParams = new URLSearchParams(paramsString);
for (var key of searchParams.keys()) {
if (key.startsWith("Loc-")) {
console.log(key, searchParams.get(key));
}
}
Here is a function you can use that accepts a parameter for what you are looking for the parameter to start with:
function getUrlParameters(var matchVal) {
var vars = [];
var qstring = window.location.search;
if (qstring) {
var items = qstring.slice(1).split('&');
for (var i = 0; i < items.length; i++) {
var parmset = items[i].split('=');
if(parmset[0].startsWith(matchVal)
vars[parmset[0]] = parmset[1];
}
}
return vars;
}

Count the number of parameters in query string

How can I count the number of parameters query strings passed? e.g.
www.abc.com/product.html?product=furniture&&images=true&&stocks=yes
I want to be able to get the answer as 3
1. product=furniture
2. images=true
3. stocks=yes
var url = window.location.href;
var arr = url.split('=');
console.log(url.length)
You can use String's match:
var matches = str.match(/[a-z\d]+=[a-z\d]+/gi);
var count = matches? matches.length : 0;
first get the location of a question mark character ? in the required url
var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);
then get the array of parameters:
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
Then count the length of result as
result.length;
If you're using express you can use
Object.keys(req.query).length
see here: How to get number of request query parameters in express.js?
You could use the search variable in the document.location object to get the search string and then use a match on the '=' symbols to get a count (see example below)
var paramCount = document.location.search.match(/=/g).length;
How about the URLSearchParams interface that provides utility methods to work with the query string of a URL?
Something like that:
var url_string = window.location.href;
var url_var = new URL(url_string);
var params = url_var.searchParams;
var param_count = 0;
for (const [key, value] of params.entries()) {param_count++;}

How to obtain the query string from the current URL with JavaScript?

I have URL like this:
http://localhost/PMApp/temp.htm?ProjectID=462
What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript?
What I've done so far is this:
var url = window.location.toString();
url.match(?);
I don't know what to do next.
Have a look at the MDN article about window.location.
The QueryString is available in window.location.search.
If you want a more convenient interface to work with, you can use the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.
let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);
searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true
The URLSearchParams interface is now widely adopted in browsers (95%+ according to Can I Use), but if you do need to support legacy browsers as well, you can use a polyfill.
Use window.location.search to get everything after ? including ?
Example:
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
If you happened to use Typescript and have dom in your the lib of tsconfig.json, you can do:
const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');
// To append, you can also leverage api to avoid the `?` check
params.append('newKey', 'newValue');
You can use this for direct find value via params name.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
This will add a global function to access to the queryString variables as a map.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
window.location.query = function (source) {
var map = {};
source = source || this.search;
if ("" != source) {
var groups = source, i;
if (groups.indexOf("?") == 0) {
groups = groups.substr(1);
}
groups = groups.split("&");
for (i in groups) {
source = groups[i].split("=",
// For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
(groups[i].slice(-1) !== "=") + 1
);
// Key
i = decodeURIComponent(source[0]);
// Value
source = source[1];
source = typeof source === "undefined"
? source
: decodeURIComponent(source);
// Save Duplicate Key
if (i in map) {
if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
map[i] = [map[i]];
}
map[i].push(source);
}
// Save New Key
else {
map[i] = source;
}
}
}
return map;
}
window.location.query.makeString = function (source, addQuestionMark) {
var str = "", i, ii, key;
if (typeof source == "boolean") {
addQuestionMark = source;
source = undefined;
}
if (source == undefined) {
str = window.location.search;
}
else {
for (i in source) {
key = "&" + encodeURIComponent(i);
if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
str += key + addUndefindedValue(source[i]);
}
else {
for (ii = 0; ii < source[i].length; ii++) {
str += key + addUndefindedValue(source[i][ii]);
}
}
}
}
return (addQuestionMark === false ? "" : "?") + str.substr(1);
}
function addUndefindedValue(source) {
return typeof source === "undefined"
? ""
: "=" + encodeURIComponent(source);
}
}
Enjoy.
You can simply use URLSearchParams().
Lets see we have a page with url:
https://example.com/?product=1&category=game
On that page, you can get the query string using window.location.search and then extract them with URLSearchParams() class.
const params = new URLSearchParams(window.location.search)
console.log(params.get('product')
// 1
console.log(params.get('category')
// game
Another example using a dynamic url (not from window.location), you can extract the url using URL object.
const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')
console.log(url.search)
// ?v=6xJ27BtlM0c&ab_channel=FliteTest
This is a simple working snippet:
const urlInput = document.querySelector('input[type=url]')
const keyInput = document.querySelector('input[name=key]')
const button = document.querySelector('button')
const outputDiv = document.querySelector('#output')
button.addEventListener('click', () => {
const url = new URL(urlInput.value)
const params = new URLSearchParams(url.search)
output.innerHTML = params.get(keyInput.value)
})
div {
margin-bottom: 1rem;
}
<div>
<label>URL</label> <br>
<input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
</div>
<div>
<label>Params key</label> <br>
<input type="text" name="key" value="v">
</div>
<div>
<button>Get Value</button>
</div>
<div id="output"></div>
You can use this function, for split string from ?id=
function myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id=");
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");
here is the fiddle
window.location.href.slice(window.location.href.indexOf('?') + 1);
You can use the search property of the window.location object to obtain the query part of the URL. Note that it includes the question mark (?) at the beginning, just in case that affects how you intend to parse it.
You should take a look at the URL API that has helper methods to achieve this in it as the URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
This is not currently supported by all modern browsers, so don't forget to polyfill it (Polyfill available using https://qa.polyfill.io/).
var queryObj = {};
if(url.split("?").length>0){
var queryString = url.split("?")[1];
}
now you have the query part in queryString
First replace will remove all the white spaces, second will replace all the '&' part with "," and finally the third replace will put ":" in place of '=' signs.
queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
So let say you had a query like abc=123&efg=456. Now before parsing, your query is being converted into something like {"abc":"123","efg":"456"}. Now when you will parse this, it will give you your query in json object.
8 years later, for a one-liner
const search = Object.fromEntries(new URLSearchParams(location.search));
Down-side, it does NOT work with IE11
To explain
The URLSearchParams interface defines utility methods to work with the query string of a URL. (From , https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
The Object.fromEntries() method transforms a list of key-value pairs into an object. (From, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)
// For https://caniuse.com/?search=fromEntries
> Object.fromEntries(new URLSearchParams(location.search))
> {search: "fromEntries"}
Convert that into array then split with '?'
var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';
url.split('?')[1]; //ProjectID=462
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
Try this one
/**
* Get the value of a querystring
* #param {String} field The field to get the value of
* #param {String} url The URL to get the value from (optional)
* #return {String} The field value
*/
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
Let’s say your URL is http://example.com&this=chicken&that=sandwich. You want to get the value of this, that, and another.
var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null
If you want to use a URL other than the one in the window, you can pass one in as a second argument.
var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'
Reference
I think it is way more safer to rely on the browser than any ingenious regex:
const parseUrl = function(url) {
const a = document.createElement('a')
a.href = url
return {
protocol: a.protocol ? a.protocol : null,
hostname: a.hostname ? a.hostname : null,
port: a.port ? a.port : null,
path: a.pathname ? a.pathname : null,
query: a.search ? a.search : null,
hash: a.hash ? a.hash : null,
host: a.host ? a.host : null
}
}
console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( 'https://example.com?qwery=this').query )
This will return query parameters as an associative array
var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
if(query[i]){
var temp = query[i].split("=");
queryParams[temp[0]] = temp[1]
}
}
For React Native, React, and For Node project, below one is working
yarn add query-string
import queryString from 'query-string';
const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");
console.log(parsed.offset) will display 10

Categories

Resources