I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();
Related
I'm trying to fetch data based on the url.
Everything works except on: let urlFilters.
What I'm trying to do:
iterate over the array: filters (if it's not null)
save output in: let urlFilters
By now, the iteration seem to work. When I console.log(urlFilters) I get key-value-pairs like "filter=orange" or "filter=apple?". The problem: only the last key-value-pair is saved and thus used for the url.
My question: how can I save all the key-value-pairs from the iteration and use them all in the url?
const getInfo = async(filters, searchTerm) => {
let url = "";
let urlBasis = "/api/productInfo?";
let urlSearchTerm = "";
let urlFilters = "";
if (searchTerm.length !== 0) {
...
} else {
...
};
//problem
if (filters.length !== 0) {
filters.forEach((filterItem, index) => {
urlFilters = `filter=${filterItem.categoryUrl}${index === filters.length -1 ? "" : "&"}`
//console.log(urlFilters) -> "filter=orange" or "filter=apple&"
});
} else {
urlFilters = ""
};
try {
//problem urlFilters: shows only the last key-value pair
url = urlBasis + urlSearchTerm + `${searchTerm.length !== 0 && filters.length !== 0 ? "&" : ""}` + urlFilters
} catch (err) {
console.log(err);
}
};
I already tried to use .map instead of .forEach. I also tried to use the spread operator. But it didn't work and I'm a little stuck. Any suggestions (also for code improvement) are appreciated. Thanks a lot!
If I understand the question correctly, you can iterate over your array easier via .map and then merge the array into a single string using .join():
const data = [{url: "apple"}, {url: "banana"}]
const url = `http://myurl.com?${data.map(item => `filter=${item.url}&`).join('').slice(0, -1)}`
console.log(url)
Note that .slice() ist needed to cut the last & character off the string.
So I think my previous approach wasn't the best.
It seems as the URLSearchParams-API is a simpler approach when working with urls and params - at least with this solution the code works and looks cleaner.
Here is what I have now:
const getInfo = async (filters, searchTerm) => {
let url = "/api/productInfo?";
let params = new URLSearchParams();
if(searchTerm.length !== 0) {
//logic
};
if(filters.length !== 0) {
filters.forEach((filterItem) => {
params.append("filter", filters.categoryUrl);
});
};
try {
url = url + params;
console.log("url", url);
...
}
}
I'm passing an object using the jQuery $.post method. When it's loaded using the $.get method, I need that the message field of the object is parsed correctly. I was able to remove the equal "=" sign and the "&" sign, but if it's a long message it will contain the plus "+" sign and the commas are not displayed correctly. Here is the console output i get:
{user: "demo", message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipisci…+qui+officia+deserunt+mollit+anim+id+est+laborum."}
message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipiscing+elit%2C+sed+do+eiusmod+tempor+incididunt+ut+labore+et+dolore+magna+aliqua.+Ut+enim+ad+minim+veniam%2C+quis+nostrud+exercitation+ullamco+laboris+nisi+ut+aliquip+ex+ea+commodo+consequat.+Duis+aute+irure+dolor+in+reprehenderit+in+voluptate+velit+esse+cillum+dolore+eu+fugiat+nulla+pariatur.+Excepteur+sint+occaecat+cupidatat+non+proident%2C+sunt+in+culpa+qui+officia+deserunt+mollit+anim+id+est+laborum."
user: "demo"
__proto__: Object
The commas are replaced by the %2C character and the spaces are replaced from the plus sign.
How to obtain the text without this signs?
here is a function I write for this scope, but it's not working at all.
function parseData(data){
var params = {}
params.data = data.split("&");
params.result = {};
for(var i = 0; i < params.data.length; i++) {
var item = params.data[i].split("=");
params.result[item[0]] = item[1];
}
return params.result;
}
Use this one :
function parseData(data){
return decodeURIComponent((data + '').replace(/\+/g, '%20'));
}
Use this function hope it will work for you :
export function parseData(data) {
url = decodeURI(url);
if (typeof url === 'string') {
let params = url.split('?');
let eachParamsArr = params[1].split('&');
let obj = {};
if (eachParamsArr && eachParamsArr.length) {
eachParamsArr.map(param => {
let keyValuePair = param.split('=')
let key = keyValuePair[0];
let value = keyValuePair[1];
obj[key] = value;
})
}
return obj;
}
}
I have a string that I need to search for within a json object and return back a specific hash number from that found value. I got it to work without underscore, but it's poorly optimized. What I need to do is stop the loop as soon as the fileToSearch string is found.
For example, I have a json object here:
var json = {
"images/mike.jpg" : "images/mike.12345.jpg",
"images/joe.jpg" : "images/joe.axcvas.jpg",
"images/mary.jpg" : "images/mary.mndfkndf.jpg",
"images/jane.jpg" : "images/jane.dfad34.jpg",
};
And I have a variable fileToSearch that I need to look for in the above object.
var fileToSearch = "joe.jpg";
What should get outputted is the hash value in images/joe.axcvas.jpg, so axcvas.
Without underscore:
var hash;
for (var key in json) {
var index = key.indexOf(fileToSearch);
if (index !== -1) {
hash = json[key].split('.')[1];
}
}
console.log(hash); //axcvas
How can I optimize/achieve this with Underscore?
You can use _.findKey in such way:
var key = _.findKey(json, function(value, key) {
return key.indexOf(fileToSearch) >= 0;
});
var hash = key? json[key].split('.')[1] : undefined;
Note that this method is available since v1.8.0.
You can break the loop when you find the element
var hash;
for (var key in json) {
var index = key.indexOf(fileToSearch);
if (index !== -1) {
hash = json[key].split('.')[1];
break;
}
}
console.log(hash);
I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)
I have an object with multiple properties, I want to wrap the results in single quotes and commas if there are multiple values please see the following fiddle.
http://jsfiddle.net/efv7sh9d/1/
var obj = {
WKF001: ['test1'],
WKF002: ['test2','test3'],
WKF003: ['test4','test5','test6','test7'],
WKF004: ['test8','test8','test9','test10','test11'],
WKF005: ['test12','test13','test14','test15','test16']
}
function returnCodes(wkf, obj) {
for (var d in obj) {
if (d.indexOf(wkf) > -1) {
return obj[d];
}
}
return 'Unknown';
}
var wkftest1 = "WKF001";
var wkftest2 = "WKF002";
var wkftest3 = "WKF003";
document.write(returnCodes(wkftest3, obj).join("','"));
This will return test4','test5','test6','test7 and I need it to be 'test4','test5','test6','test7'
document.write("'" + returnCodes(wkftest3, obj).join("','") + "'");
This is a common idiom in any language with an array join method/function.