This question already has answers here:
How to get GET (query string) variables in Express.js on Node.js?
(26 answers)
Closed 5 years ago.
Let's say my url atm is
http://test.com/?city=toronto
I'm able to get the requestURL string that is
/?city=toronto
From here, I was wondering if there is a built in function or a standard procedure of extracting the word "toronto" or any other word that comes after the = from the string.
A standard procedure (as you mentioned) of doing this, you can get all the parameter values including value of city or any other parameter you may add to it.
var values = new URL('http://test.com/?city=toronto').searchParams.values();
for(var value of values){
console.log(value);
}
UPDATE
As #taystack mentioned in the comment, if you only want the value of a specific parameter (city) in this case, you can use:
new URL('http://test.com/?city=toronto').searchParams.get('city');
Use split();
var url = '/?city=toronto'.split('=');
console.log(url[1]);
Node.js has a new module called URL, which encodes the semantics of a url string. You don’t need to do any string manipulation.
const URL = require('url')
let my_url = new URL('http://test.com/?city=toronto')
URL#search returns the string representing the search:
my_url.search // '?city=toronto'
URL#query returns the search string excluding ?:
my_url.query // 'city=toronto'
and URL#searchParams returns an object encoding the search string:
my_url.searchParams // something kind of like {'city':'toronto'}
my_url.searchParams.get('city') // 'toronto'
my_url.searchParams.keys() // ['city'] (all the keys)
my_url.searchParams.values() // ['toronto'] (all the values)
Related
This question already has an answer here:
PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()
(1 answer)
Closed 1 year ago.
Hii ha ve written this question because i have a json converted to a string with a function of php called json_encode()
Something like this:
{ "data":"2","state":"false"}
when the original json that im trying to encode is like this:
{ "data":2,"state":false}
(Please note that the type of the variables are different, in the original i have an int number called data and boolean called state, but when i use json_encode() every variable goes to a string..)
The problem is when i try to json.PARSE() the value from the json encode of php in angular i don´t get the correct value, every variable is a string...
For example, isntead of getting the boolean state of the variable, i get "false" or "true", and this is a problem...
There is a way to parse this avoiding this problem? basically my problem is when i parse the json in my angular project i dont get the correct type of variable..
Thanks!
You can use JSON.parse on an individual value to convert it into the desired type:
const oldValue = JSON.parse('{"data":"2","state":"false"}')
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = JSON.parse(oldValue[key]);
});
Here's the other way around:
const oldValue = JSON.parse('{"data": 2,"state": false}');
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = oldValue[key].toString();
});
Note: These examples assume flat objects. You'd need to recurse through the object's tree if some of the values are objects, for example {a: {b: "c"}}.
This question already has answers here:
Split and parse window.location.hash
(3 answers)
Closed 2 years ago.
I have this url that is provided by the chrome.identity.getRedirectURL() function
https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600
I need to get the access_token param value to store the token and use it later with spotify api. What is the best method I can use in javascript?
If you have a url like https://some-url?access_token=1234 you can use URLSearchParams.
// window location search returns '?access_token=1234' if the url is 'https://some-url?access_token=1234'
const params = new URLSearchParams(window.location.search);
const token = params.get('access_token');
Update Regex
const x = new RegExp(/(#access_token=).*?(&)+/);
const str = 'https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600';
// Use String.prototype.match and pass the Regex
const result = String(str).match(x);
console.log(result);
// returns
[
"#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5…9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&",
"#access_token=", "&",
index: 57,
input: "https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiuma…1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600",
groups: undefined
]
// Access the matching substring if there is one using
result[0];
// "#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&"
PLEASE NOTE THAT THE BEGINNING # AND ENDING & ARE INCLUDING WITH THIS REGULAR EXPRESSION.
I'm looking for a way to get the query string part of a url using node.js or one of it's extension module.
I've tried using url and express but they give me an array of parameters.
I want to original string.
Any ideas ?
example; for:
http://www.mydom.com?a=337&b=33
give me
a=337&b=33
(with or without the ?)
Use url.parse. By default it will return an object whose query property is the query string. (You can pass true as the second argument if you want query to be an object instead, but since you want a string the default is what you want.)
var url = require('url');
var urlToParse = 'http://www.mydom.com/?a=337&b=33';
var urlObj = url.parse(urlToParse);
console.log(urlObj.query);
// => a=337&b=33
How about using the built-in url.parse method?
I need to extract a particular cookie from page cookies in Javascript. I get them in one long string as a passed variable. String is of the format
"xyz=1; abc=2; abc-main=3"
I need to extract the value of one particular cookie from this string say "abc". What is the best way to do it, is there any function that directly gives you the cookie value?
I'm thinking of splitting this string with semicolon and then traversing the result array to find a string that starts with "abc="
Your idea is good.
You could split semicolon and space and later split again results with equal symbol and create an object with results so you can make access to properties so easy:
//cookieString is "xyz=1; abc=2; abc-main=3"
cookieSplit = cookieString.split("; ");
var cookieObject = {};
cookieSplit.forEach( function(value, index) {
var splitResult = value.split("=");
cookieObject[splitResult[0]] = splitResult[1];
});
Then you can access data using cookieObject.abc or cookieObject["abc"]
Hope it helps!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get query string values in JavaScript
Parse query string in JavaScript
http://www.example.org/search?q=example&another=test&again=more
How can I create three sepearate variables in jQuery with the values example, test, and more?
In other words, how can I extract a query from a URL based on its position (first, second, third, etc.) in the URL or based on the &another= part (not sure what it's called) of the query?
I use this method:
var query = window.location.split('?')[1]; // or http://www.example.org/search?q=example&another=test&again=more
var query_obj = unserialize(query);
function unserialize(query) {
var pair, params = {};
query = query.replace(/^\?/, '').split(/&/);
for (pair in query) {
pair = query[pair].split('=');
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return params;
}
So you'll have your variables in the query_obj like this: query_obj.test
I found the function over the internet a while ago so I can't provide a link. Sorry and thanks to whoever published it first.
I use an existing plugin for tasks like these: https://github.com/allmarkedup/jQuery-URL-Parser