I am parsing a multiline value from a textarea encoded in the URL:
// URL Params:
?cn=asdf%20asdf&pn=asdf%20asdf&pe=asdf%40example.com&d=asdf%0A%0Aasdf&ye=test%40example.com&c=1234&tc=true
// JAVASCRIPT
var _url = window.location.href;
var _queryParams = decodeURIComponent( _url.split('?')[1] );
var _search = _queryParams;//location.search.substring(1);
var _data = JSON.parse('{"' + decodeURI(_search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
But I'm getting an Syntax Error: Unexpected token... error from the JSON.parse() function whenever I have a multiline text value in the d= URL param above:
&d=asdf%0A%0Aasdf
What .replace() regex pattern do I need to do to handle the line break encoding, %0A?
EDIT:
I'm already successfully converting the URL params to a javascript object. The problem is that the replace([pattern match]) functions inside are choking on the mutliline text character: %0A.
Parse the query string using URLSearchParams, and then use URLSearchParams's entries method to turn it into a plain Javascript object, and then stringify it to turn it into a JSON-formatted string:
const queryString = '?cn=asdf%20asdf&pn=asdf%20asdf&pe=asdf%40example.com&d=asdf%0A%0Aasdf&ye=test%40example.com&c=1234&tc=true';
const params = new URLSearchParams(queryString);
console.log(params.get('d'));
const queryObj = {};
for (const [key, val] of params.entries()) {
queryObj[key] = val;
}
console.log(JSON.stringify(queryObj));
Related
I have this URL : http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
and I want to get from this only the access_token value 90kzif5gr8plhtl9286sc1z1qbgoj3
How can I do it in Javascript please ?
Here is the solution:
const url = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
const hash = url.substring(url.indexOf('#') + 1);
let result = hash.split('&')
result = result[0].split('=')
console.log(result[1]); // "90kzif5gr8plhtl9286sc1z1qbgoj3"
Happy coding :)
As you can see in this the simplest way is :
var url_string = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
var url = new URL(url_string);
var c = url.searchParams.get("access_token");
You can try this by splitting the URL string into three strings and using the access token directly then
var url=http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
var firstHalf=url.split('#access_token=')[1];
var required_token=firstHalf.split("&scope")[0];
print the value of required_token.
Required result will be "90kzif5gr8plhtl9286sc1z1qbgoj3"
your text is the string contained in window.location.hash, and a string of that format can be easily turned into a properly decoded key/value store using the URLSearchParams constructor:
const token = new URLSearchParams(window.location.hash).get("access_token");
How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams object, check each parameter's value, and delete() as necessary. Finally using URL's href property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);
You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:
const str = 'https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);
I have cookie value stored in following format
{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}
and i need to read following values of
necessary
preferences
statistics
marketing
Not sure how to to read values correctly, i tried following code assuming it is jSON format
Cookies.get('CookieConsent')
//Parse the cookie to Object
cookieval = Cookies.get('CookieConsent');
console.log(cookieval);
console.log("Necessary: " + Boolean(cookieval.necessary));
console.log("Prefrences: " + Boolean(cookieval.preferences));
console.log("Statistics: " + Boolean(cookieval.statistics));
console.log("Marketing: " + Boolean(cookieval.marketing));
But this code always returns false.
I use following Jquery to read Cookie values https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js
You do not have JSON format - you have something closer to JS object literal notation, except that it's a string rather than JS code, so can't use JSON.parse unfortunately.
If the values don't have commas or colons, you can split the string by commas and reduce into an object:
const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
const obj = input
.slice(1, input.length - 1)
.split(',')
.reduce((obj, str) => {
const [key, val] = str.split(':');
obj[key] = val;
return obj;
}, {});
console.log(obj);
eval is another option, but that's unsafe.
Wrap this string by ( and ). Then parse like as display follow
Attention! But you need be ensure input string (which received from cookie) not contains bad code. Such as unknown injected function. In this case, the function will be executed on client browser, with access to private data (cookie, localStorage, data from html-forms).
const input = "{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}"
const object = eval("(" + input + ")");
alert(object.necessary);
What about massaging the string into proper JSON, parsing it into a JSON Object, and using the fields from there?
It's less stable in that changes to the input string may break the function, but it is secure in that it's calling JSON.parse() rather than eval().
function reformatCookieInput(inputString) {
inputString = inputString.replace(/'/g, ""); //global strip out single quotes currently wrapping stamp
inputString = inputString.replace(/,/g, `", "`); //global replace commas with wrapped commas
inputString = inputString.replace(/:/g, `":"`); //same idea with colons
inputString = inputString.replace("{", `{"`); //rewrap start of JSON string
inputString = inputString.replace("}", `"}`); //rewrap end of JSON string
return inputString;
}
const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
const properJSONObject = JSON.parse(reformatCookieInput(input));
console.log(properJSONObject);
How can I convert this string: "{one=1,two=2}" into an object with JavaScript? So I can access the values.
I tried replacing the "=" for ":", but then while accessing the object I receive an "undefined". Here is my code:
var numbers = "{one=1,two=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
document.write(numbers.one); //prints undefined
So this is the string
var str = '{one=1,two=2}';
replace = character to : and also make this as a valid JSON object (needs keys with double-quotes around)
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
In regex, \w means [a-zA-Z0-9_] and the ( ) capture what's inside, usable later like here with $1
Now parse your string to JSON in order to use like that
var str_json = JSON.parse(str_for_json);
Now enjoy. Cheers!!
document.write(str_json.one);
FINALLY :
var str = '{one=1,two=2}';
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
try {
var str_json = JSON.parse(str_for_json);
document.write(str_json.one);
} catch(e) {
console.log("Not valid JSON:" + e);
};
Instead of trying to use regexp to create JSON, I would simply parse the string directly, as in
const result = {};
numbers.match(/{(.*?)}/)[1] // get what's between curlies
.split(',') // split apart key/value pairs
.map(pair => pair.split('=')) // split pairs into key and value
.forEach(([key, value]) => // for each key and value
result[key] = value); // set it in the object
1 - a valide JSON is :var numbers = "{\"one\"=1,\"two\"=2}"; (you need the \")
2- you need to JSON.parse the strign
So this works:
var numbers = "{\"one\"=1,\"two\"=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
numbers=JSON.parse(numbers);
document.write(numbers.one); //prints undefined
But, it's bad practice !
Let's say I have the following url:
something.com/messages/username/id
How can I get the username or id?
You can use String.split for that:
var parts = window.location.href.split('/'); # => ["http:", "", "something.com", "messages", "username", "id"]
var username = parts[4];
var id = parseInt(parts[5]);
I guess you could use the window.location.href to get the URL and then string.split() the URL on /.
var urlParts = window.location.href.split("/");
var username = urlParts[4];
var id = urlParts[5];
I actually just had to deal with the other day. When you're accessing the cached version of some of our pages, the query string is actually part of the URL path. But if you're trying to avoid the cache, you use a query string.
Given one of the answers from How to get the value from the GET parameters? here's what I'm using to partially normalize access.
The router that takes the response does _.isArray() (we're built on top of backbone, so we have underscore available) and handles pulling the data out of the object or array in a different manner.
The slice at the end gets rid of the two "" since we're not using documents, just directories and our URLs start and end with /. If you're looking for document access, you should alter the slice accordingly.
var qs = function(){
if(window.location.search){
var query_string = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
})();
} else {
return window.location.pathname.split('/').slice(1, -1);
}
return query_string;
};
You could split your url on every '/' character like this:
var url = "something.com/messages/username/id";
var array = url.split('/');
// array[2] contains username and array[3] contains id