This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
Closed 4 years ago.
I have the following url of my html page, and I am looking for a way to get the value "1997" passed into a string using javascript.
I am thinking of using Regex, but isn't there a much simpler way?
http://localhost:8080/App/sample?proj=1997
Here is a quick function using split and a for loop.
function getParam (url, param) {
try {
/* Get the parameters. */
var params = url.split("?")[1].split("&");
/* Iterate over each parameter. */
for (var i = 0, l = params.length; i < l; i++) {
/* Split the string to a key-value pair */
var pair = params[i].split("=");
/* Check whether the param given matches the one iterated. */
if (pair[0] == param) return pair[1];
}
} catch (e) {}
/* Return null, if there is no match. */
return null;
}
/* Example. */
console.log(
getParam("http://localhost/dir/file", "proj"),
getParam("http://localhost:8080/App/sample?proj=1997", "proj")
);
Related
This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.
This question already has answers here:
How to get function parameter names/values dynamically?
(34 answers)
Closed 6 years ago.
I'm trying to grab an array of string represented parameters from a function and I'm unsure how to proceed. Basically given the function below
function MyFunc(param1, param2, param3){
//do all the things
}
What would the function "getParams" look like to do the following
getParams(MyFunc) // ["param1","param2","param3"]
This is a bit messy, but you can do this by converting your function to a string and then splitting it until you get just the parameters:
var getFuncParams = function(MyFunc) {
var str = MyFunc.toString()
var strParams = str.substr((str.indexOf('(')+1), (str.indexOf(')') - str.indexOf('(')) - 1)
var params = strParams.split(",")
return params;
}
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I want to parse a string to an object object selector like so :
var test = 'object.prop1.prop2';
into
object['prop1']['prop2'];
The problem is i don't know how many properties the string could have.
What is the best way to to parse a string accross, idealy without something like json parse/ eval?
There is a package for that :
https://www.npmjs.com/package/object-path
Juhana's link is excellent, but also a bit more of a complex problem than the one you have here. Here is my take (https://jsfiddle.net/gm32f6fp/3/):
var object = {
prop1: {
prop2: {
foo: 1
}
}
};
function get(object, key) {
var keys = key.split('.');
for (var i = 0; i < keys.length; i++) {
if (!object.hasOwnProperty(keys[i])) {
return null;
}
object = object[keys[i]];
}
return object;
}
console.log(get(object, 'prop1.prop2'));
console.log(get(object, 'prop1.prop3'));
The idea is to take the string of keys, split it based on the dot. Then you have an arbitrarily large array of keys, so we take each key, one by one, and dive into the object. (If we end up at a dead end, we bail out.)
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
I have a form that uses the get method and contains an array:
http://www.example.com?name[]=hello&name[]=world
I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.
I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.
Is it possible to get array values?
There you go: http://jsfiddle.net/mm6Bt/1/
function getURLParam(key,target){
var values = [];
if (!target) target = location.href;
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var pattern = key + '=([^&#]+)';
var o_reg = new RegExp(pattern,'ig');
while (true){
var matches = o_reg.exec(target);
if (matches && matches[1]){
values.push(matches[1]);
} else {
break;
}
}
if (!values.length){
return null;
} else {
return values.length == 1 ? values[0] : values;
}
}
var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';
console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 8 years ago.
I have a a function that takes a string like "obj.key.subkey.subsubkey":
function(obj, key) {
return eval('obj.'+ key);
}
What would be a safe alternative to eval in this case or is eval fine? new Function won't work in this case AFAIK. Maybe split and loop then?
I'm not sure you really need a function here. If you have the object and the key just use the key to return the property on the object.
obj[key]
If you must handle multiple keys:
function get(obj, key) {
var keys = key.split(".");
var tmp = obj;
for (var x = 0; x < keys.length; x++){
tmp = tmp[keys[x]];
}
return tmp;
}
Working Example: http://jsfiddle.net/H55ka/