How to Extract URL content using Rails or Javascript - javascript

I have this question its easy to add content to url but how to extract it
http://localhost:3000/pages/wish?url=file:///Users/ruelnopal/Desktop/sitetest/index.html&image=http://zalora-media-live-ph.s3.amazonaws.com/product/89/6948/1.jpg&price=PHP%C2%A0799.00&desc=Polo%20shirt%20with%20contrast%20tip,%20Collared%20neckline,%20Unlined,%20Regular%20fit&title=Pique%20Tipping%20Polo%20Shirt&display=popup
im trying to extract the url, image

Here's a simple implementation:
const queryString = location.search.substring(1) //the part after the "?"
const queryParams = queryString.split('&')
//Creates a mapping of params to values
const query = new Map(queryParams.map(param => param.split('=')))
console.log(query.get('url')) //"file:///Users/ruelnopal/Desktop/sitetest/index.html"
console.log(query.get('image')) //"http://zalora-media-live-ph.s3.amazonaws.com/product/89/6948/1.jpg"

Here's a function that will return all params in the URL
function getUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}

Try using the OpenURI module
require "open-uri"
File.open('my_image.png', 'wb') do |fo|
fo.write open("https://upload.wikimedia.org/wikipedia/commons/5/53/Wikipedia-logo-en-big.png").read
end

Related

I want to add a countdown to a webpage using an parameter from a link

We are using niftyimages to add countdowns on our emails and would like to use a countdown on our webpage. We would like to make it personalized to the individual when they click on a link from the email to the landing page.
So if we have a link: www.webpage.com?dt=2021-06-01
I tried this code:
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// set parameter name and value (use 'true' if empty)
var paramName = a[0];
var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
// if the paramName ends with square brackets, e.g. colors[] or colors[2]
if (paramName.match(/\[(\d+)?\]$/)) {
// create key if it doesn't exist
var key = paramName.replace(/\[(\d+)?\]/, '');
if (!obj[key]) obj[key] = [];
// if it's an indexed array e.g. colors[2]
if (paramName.match(/\[\d+\]$/)) {
// get the index value and add the entry at the appropriate position
var index = /\[(\d+)\]/.exec(paramName)[1];
obj[key][index] = paramValue;
} else {
// otherwise add the value to the end of the array
obj[key].push(paramValue);
}
} else {
// we're dealing with a string
if (!obj[paramName]) {
// if it doesn't exist, create property
obj[paramName] = paramValue;
} else if (obj[paramName] && typeof obj[paramName] === 'string'){
// if property does exist and it's a string, convert it to an array
obj[paramName] = [obj[paramName]];
obj[paramName].push(paramValue);
} else {
// otherwise add the property
obj[paramName].push(paramValue);
}
}
}
}
return obj;
}
console.log(getAllUrlParams("https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd"));
The image from niftyimages is <img src="https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd" />
I've isolated dt=2021-06-01, what do I do to replace the "dt=2021-07-21" part in the image url?
Just to keep your code uber simple you could add an id to your img tag like this:
<img id="niftyImg" src="nifty.com?dt=2021-05-02" />
and then do something like this for your JS:
document.addEventListener("DOMContentLoaded", function(event){
var url = new URL(window.location.href);
var dt = url.searchParams.get("dt");
var element = document.getElementById("niftyImg");
var regex = /[0-9]+-[0-9]+-[0-9]+/gm;
element.src = element.src.replace(regex, dt);
});
What this does is waits for the DOM to finish loading then grabs the query parameter off the url, finds your image tag on the page and replaces the date in your src attribute with the one in the url. There's probably slicker ways of doing the regex in case you might have something other than a date there but this will likely get you in the ballpark of what you're trying to do. There may be a flash of the image on page load of the old date but then once the javascript executes the image will update to the new date. If you don't want that flash you would want to do something server-side before the page is rendered if that's an option.
How about using replace and template ${literals}.
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// set parameter name and value (use 'true' if empty)
var paramName = a[0];
var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
// if the paramName ends with square brackets, e.g. colors[] or colors[2]
if (paramName.match(/\[(\d+)?\]$/)) {
// create key if it doesn't exist
var key = paramName.replace(/\[(\d+)?\]/, '');
if (!obj[key]) obj[key] = [];
// if it's an indexed array e.g. colors[2]
if (paramName.match(/\[\d+\]$/)) {
// get the index value and add the entry at the appropriate position
var index = /\[(\d+)\]/.exec(paramName)[1];
obj[key][index] = paramValue;
} else {
// otherwise add the value to the end of the array
obj[key].push(paramValue);
}
} else {
// we're dealing with a string
if (!obj[paramName]) {
// if it doesn't exist, create property
obj[paramName] = paramValue;
} else if (obj[paramName] && typeof obj[paramName] === 'string'){
// if property does exist and it's a string, convert it to an array
obj[paramName] = [obj[paramName]];
obj[paramName].push(paramValue);
} else {
// otherwise add the property
obj[paramName].push(paramValue);
}
}
}
}
return obj;
}
function replace_url_param(url, param, replacement)
{
let params = getAllUrlParams(url);
return url.replace(`${param}=${params[param]}`, `${param}=${replacement}`)
}
let image = document.getElementById('image');
image.addEventListener('mouseover', function() {
image.src = replace_url_param("https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd", 'dt', '2021-06-05');
});
console.log(replace_url_param("https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd", 'dt', '2021-06-05'));
<img src="https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd" id="image">
Just to get started, there are easier things to do. just use the URL API
sample code
var URL_val = "https://img1.niftyimages.com/q24/9jso/fjad?dt=2021-07-21&format=yyyy-MM-dd"
, URL_Obj = new URL(URL_val)
;
for (let [name,value] of URL_Obj.searchParams)
{
console.log(`_.name: ${name}, _.val: ${value}`)
}
let dateParam = URL_Obj.searchParams.get('dt')
console.log(`dateParam: ${dateParam}`)

Converting a badly stringfied json to a json object

I have some data i am pulling from a web service. This is the string
(Body:'3886' MessageProperties [headers={}, timestamp=null,
messageId=null, userId=null, receivedUserId=null, appId=null,
clusterId=null, type=null, correlationId=null,
correlationIdString=null, replyTo=null,
contentType=application/x-java-serialized-object,
contentEncoding=null, contentLength=0, deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0,
redelivered=false, receivedExchange=,
receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62,
messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,
consumerQueue=bottomlesspit])
It looks like json but the key value pairs are almost fine but the most important key which is Body isn't like other keys as the string would tell.
I need to read the value of Body and be able to get the value like this
console.log(d.body);
//This above outputs the string as shown
obj = eval('{' + d.body + '}');
console.log(obj);
var match = "Body";
var val = obj.find( function(item) { return item.key == match } );
console.log(val);
How can i read the value of the key Body?.
Use this regular expression instead of a match Body:
\bBody:'(\d*)'
This will catch the Body number in group 1.
You can write a parser function get string and extract values. A very simple function is here. You can modify it also for all exceptions exist.
var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;
function f(inp) {
var index = str.indexOf(inp),
endIndex;
for(var i = index; i < str.length; i ++) {
if(str[i] == ',') {
endIndex = i;
break;
}
}
var output = str.substr(index, endIndex).split('=');
return output;
}
console.log(f('consumerQueue'));
Why not use a regex to match and extract the Body.
Example:
const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
const body = match[1] // This is the value of Body
} else {
// Unable to find Body, handle it here
}

Set dropdown value based on url parameter

I need to set dropdown list item basing to url parameter.
I have this javascript script, which extracts parameter from url:
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
It's getting the parameter correctly, but Im not able to setup IFs to change dropdown value.
Here is HTML
<div class="form-group">
<div class="col-xs-6 col-sm-3">
<asp:DropDownList runat="server" ID="ddlSite2" CssClass="form-control" AutoPostBack="false" >
<asp:ListItem Text="Job Start" Value="3" />
<asp:ListItem Text="In Progress" Value="1" />
<asp:ListItem Text="Final Inspection" Value="2" />
</asp:DropDownList>
</div>
</div>
And my javascript code that does not work:
var endpage = getAllUrlParams().endpage;
if ( endpage.value = "logininprogress" ) {
document.getElementById('ddlSite2').value = '1';
}
if ( endpage.value = "loginfinal" ) {
document.getElementById('ddlSite2').value = '2';
}
if (endpage.value = "loginjobstart" ) {
document.getElementById('ddlSite2').value = '3';
}
URL: https://localhost/blabla/bla/endpage=logininprogress
You are setting endpage.value instead of checking it. In JavaScript = sets a value and === is used to check equality.
Change endpage.value = "logininprogress" to endpage.value === "logininprogress" and make the same change for your other if statements.

javascript modify url parameter array

I have a url with an array in it as parameter. For example:
test.dev/orders?filter[]=temp&filter[]=placed
I want to create a js function that can toggle the contents of the array and redirects after the modification.
For example, if i call a function toggleFilter('temp') i want the js to redirect to test.dev/orders?filter[]=placed.
But if i call toggleFilter('processed') i want to have the js redirect to test.dev/orders?filter[]=temp&filter[]=placed&filter[]=processed.
How can i make such function? Thanks in advance!
The function needs to get the current query string, break it down, and then based on the parameters, re-assemble it.
document.location.search - gives you the query string easily enough.
String.split - lets you break it down into its parts.
arguments - lets use this instead of defined parameters so you can pass as many (or as few) filters as you like.
From there, its just interpreting the parameters to assemble a new query string...
function toggleFilter() {
var queryString = document.location.search;
queryString = queryString.substring(1); // Get rid of the initial '?'
// Break it into individual parts and remove the 'filter[]=' leaving just the values
var queryStringSplit = queryString.split('&');
var values = [];
for (var qss = 0; qss < queryStringSplit.length; qss++) {
var value = queryStringSplit[qss];
value = value.split('=')[1];
// This will remove any "blank" values (like 'filter[]=&...")
if (value)
values.push(value);
}
// Add / remove values in arguments
for (var a = 0; a < arguments.length; a++) {
var arg = arguments[a];
var index = values.indexOf(arg);
if (index == -1)
values.push(arg);
else
values.splice(index, 1);
}
// Re-assemble the new query string
queryString = ''; // Default to blank
if (values.length)
queryString = 'filter[]=' + values.join('&filter[]=');
// Redirect to new location
location.search = queryString;
}
Having said that, I think that if you want to make this any kind of reusable, I would call it something like toggleQueryString and modify the logic to interpret the first argument as the name of the queryString value to toggle (so you could do things other than "filter[]") and I would not have it set the location, but instead return a query string value that you could do whatever you want with. But this function should do the trick.
function toggleFilter(url, key) {
var result;
if(url.indexOf('filter[]=' + key) > -1)
result = url.replace('filter[]=' + key + '&', '').replace('filter[]=' + key, '');
else
result = url + (url.indexOf('?') > -1 ? '&' : '?') + 'filter[]=' + key;
result = result.indexOf('?') == result.length - 1 ?
result.substring(0, result.length - 1) :
result;
return result;
// or if you want to redirect just write window.location.href = result;
}

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