How to check an input words against several arrays in Javascript - javascript

I need to test all the words entered into an input against 3 objects and determine which array they belong to so I can output a URL to an API.
I want to achieve this with Javascript/jQuery.
For example if the input had these words: keyword1 keyword2 keyword3 keyword5
All keyword entries will be added from a autocomplete plugin.
I then need to test them against 3 arrays.
var array1 = ["keyword2", "keyword6"];
var array2 = ["keyword3", "keyword4"];
var array3 = ["keyword1", "keyword5"];
I need to determine what array they came from so I can output a URL and add the values to specific keys in a URL.
Example:
domain.com/api?array1= [insert keyword(s)] &array2= [insert keyword(s)] &array3= [insert keyword(s)]
The keywords need to be sent as an array and must have spaces replaced with dashes.
I am using jQuery to perform a GET request with the URL generated.

You can make the code shorter by creating an array of arrays but this works
var input = "keyword1 keyword2 keyword3 keyword5".split(" ");
var array1 = ["keyword2", "keyword6"];
var array2 = ["keyword3", "keyword4"];
var array3 = ["keyword1", "keyword5"];
var arr1=[],arr2=[],arr3=[];
$.each(input,function(_,keyword) {
if ($.inArray(keyword,array1) !=-1) arr1.push(keyword);
if ($.inArray(keyword,array2) !=-1) arr2.push(keyword);
if ($.inArray(keyword,array3) !=-1) arr3.push(keyword);
});
var url = "domain.com/api/?",keywords="";
if (arr1.length>0) keywords += "&array1="+arr1.join(",");
if (arr2.length>0) keywords += "&array2="+arr2.join(",");
if (arr3.length>0) keywords += "&array3="+arr3.join(",");
if (keywords.length>0) url += keywords.substring(1).replace(/ /g,"-");
console.log(url)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You can put all the array objects into a parent array and then loop it
var parentArray = [
["keyword2", "keyword6"],
["keyword3", "keyword4"],
["keyword1", "keyword5"]
]
$.each(parentArray,function(key,value){
//here you can check
$.each(value,function(key1,value1){
if('your key word') == value1{
// then the array you are looking for would be "key" of that particular loop
}
});
});
EDIT: Now, this should definitely work

Here's a vanilla JS version:
var words = 'keyword1 keyword2 keyword3 keyword5';
// first create an object that contains your arrays
var dict = {
array1: ["keyword2", "keyword6"],
array2: ["keyword3", "keyword4"],
array3: ["keyword1", "keyword5"]
}
// start building up a new object that mirrors the existing one
// but that only contains those keywords that are in the input string
function buildURLObj(dict, words) {
var out = {};
// split the keywords string into an array
words = words.split(' ');
// loop over the object
for (var p in dict) {
out[p] = [];
// loop over the array of keywords
for (var i = 0, l = words.length; i < l; i++) {
// if the keyword in the array, push it to the
// temporary object
if (dict[p].indexOf(words[i]) > -1) {
out[p].push(words[i]);
}
}
}
// return the completed URL using createURL
return createURL(out);
}
// create a URL from the new object
function createURL(arr) {
var url = [];
for (var p in arr) {
// if the array is not empty, don't add it to the completed URL
// otherwise start building up the URL string
if [arr[p].length) {
var subURL = [];
subURL.push(p);
subURL.push('[' + arr[p].join('-') + ']');
url.push(subURL.join('='));
}
}
// return the completed URL
return url.join('&');
}
// "array1=[keyword2]&array2=[keyword3]&array3=[keyword1-keyword5]"
buildURL(dict, words);
DEMO

Related

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
Michał

How Do I Parse a Pipe-Delimited String into Key-Value Pairs in Javascript

I want to parse the following sort of string into key-value pairs in a Javascript object:
var stringVar = 'PLNC||0|EOR|<br>SUBD|Pines|1|EOR|<br>CITY|Fort Myers|1|EOR|<br>';
Each word of 4 capital letters (PLNC, SUBD, and CITY) is to be a key, while the word(s) in the immediately following pipe are to be the value (the first one, for PLNC, would be undefined, the one for SUBD would be 'Pines', the one for CITY would be 'Fort Myers').
Note that '|EOR|' immediately precedes every key-value pair.
What is the best way of doing this?
I just realised it's technically a csv format with interesting line endings. There are limitations to this in that your variable values cannot contain any | or < br> since they are the tokens which define the structure of the string. You could of course escape them.
var stringVar = 'PLNC||0|EOR|<br>SUBD|Pines|1|EOR|<br>CITY|Fort Myers|1|EOR|<br>';
function decodeString(str, variable_sep, line_endings)
{
var result = [];
var lines = str.split(line_endings);
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var variables = line.split(variable_sep);
if (variables.length > 1) {
result[variables[0]] = variables[1];
}
}
return result;
}
var result = decodeString(stringVar, "|", "<br>");
console.log(result);
If you have underscore (and if you don't, then just try this out by opening up your console on their webpage, because they've got underscore included :)
then play around with it a bit. Here's a start for your journey:
_.compact(stringVar.split(/<br>|EOR|\|/))
Try
function parse(str) {
var str = str.replace(/<br>/gi);
console.log(str);
var arr = str.split('|');
var obj = {};
for (var i=0; i<arr.length; i=i+4) {
var key = arr[i] || '';
var val_1 = arr[i+1] || '';
var val_2 = arr[i+2] || '';
if(key) {
obj[key] = val_1 + ':' + val_2; //or similar
}
}
return obj;
}
DEMO
This will work on the particular data string in the question.
It will also work on other data string of the same general format, but relies on :
<br> being discardable before parsing
every record being a group of 4 string elements delineated by | (pipe)
first element of each record is the key
second and third elements combine to form the value
fourth element is discardable.

Javascript : Select Element in URL with multiple instance of the same element

i need to retrieve a value from an URL in JS, my problem is in this url, the element is repeated at least twice with different value. What i need is the last one.
Example :
http://randomsite.com/index.php?element1=random1&element2=random2&element1=random3
and what i want is "random3" and NOT "random1"
I've tried url.match(/.(\&|\?)element1=(.?)\&/)[2];
But it always gives me the first one :(
I don't have the possibility to change how the url is written as this is for a browser extension.
var ws = "http://randomsite.com/index.php?element1=random1&element2=random2&element1=random3",
input = ws.split("?")[1].split("&"),
dataset = {},
val_to_find = "element1";
for ( var item in input){
var d = input[item].split("=");
if (!dataset[d[0]]){ dataset[d[0]] = new Array(); dataset[d[0]].push(d[1]); }
else{
dataset[d[0]].push(d[1]);
}
}
console.log("item: ", dataset[val_to_find][dataset[val_to_find].length -1]);
return dataset[val_to_find][dataset[val_to_find].length -1];
http://jsfiddle.net/wMuHW/
Take the minimum value (other than -1) from urlString.lastIndexOf("&element1=") and urlString.lastIndexOf("?element1="), then use urlString.substring.
Or alternately, split the string up:
var parts = urlString.split(/[?&]/);
...which will give you:
[
"http://randomsite.com/index.php",
"element1=random1",
"element2=random2",
"element1=random3"
]
...then start looping from the end of the array finding the first entry that starts with element= and grabbing the bit after the = (again with substring).
You could;
for (var result, match, re = /[&?]element1=(.+?)(\&|$)/g; match = re.exec(url);) {
result = match[1];
}
alert(result);
Id try keeping a nested array of duplicate elements
function parseQueryString() {
var elements = {},
query = window.location.search.substring(1),
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('='),
key = decodeURIComponent(pair[0]),
value = decodeURIComponent(pair[1]);
if (elements.hasOwnProperty(key)) {
elements[key].push(value);
}
else {
elements[key] = [value];
}
}
}
Used on: www.example.com?element1=hello&element2=test&element1=more
Would give you the object:
{
element1: [
"hello",
"more"
],
element2:[
"test"
]
}

How to parse data in javascript using regex?

How can I use regex in javascript to put items and its values in a array ?
This is my data sample:
battery.voltage: 13.50
battery.voltage.nominal: 12.0
beeper.status: enabled
device.type: ups
driver.name: blazer_ser
driver.parameter.pollinterval: 2
Thanks
use the below code to do that... here variable data contains your data...
data=data.split(/\n+/);
var output={};
for(var i=0;i<data.length;i++){
var a=data[i].split(/:\040+/);
output[a[0]]=a[1];
}
These codes will give you an array like below...
Array (
battery.voltage: "13.50",
battery.voltage: "12.0",
beeper.status: "enabled",
device.type: "ups",
driver.name: "blazer_ser",
driver.parameter.pollinterval: "2"
)
Example:
output['driver.name'] === "blazer_ser"
Why use regular expression, you can simply use substr and indexOf. Assuming you have your list stored in an array you can simply loop through the entries and split on the first occurrence of a colon.
var items = [...]; // Your items.
var arr = {};
for (var i = items.length - 1; i >= 0; i--) {
var key = items[i].substr(0, items[i].indexOf(':'));
var value = items[i].substr(items[i].indexOf(':') + 1).trim();
arr[key] = value;
}
This solution will only work in browsers implementing the trim method. If you want to be on the save side you can overwrite the String.prototype and add the trim method. (See Trim string in JavaScript?)
If you have your items as a string separated by newlines you can easily split it into an array through split;
var list = "battery.voltage: 13.50\n"
+ "battery.voltage.nominal: 12.0\n"
+ "beeper.status: enabled\n"
+ "device.type: ups\n"
+ "driver.name: blazer_ser\n"
+ "driver.parameter.pollinterval: 2";​​
var items = list.split(/\n/);
DEMO
Here's a solution that makes only one pass through the string data using a single regex:
var list = "battery.voltage: 13.50\n"
+ "battery.voltage.nominal: 12.0\n"
+ "beeper.status: enabled\n"
+ "device.type: ups\n"
+ "driver.name: blazer_ser\n"
+ "driver.parameter.pollinterval: 2";
function parse(data) {
var match, result = {};
var pattern = /\s*([^:\s]+)\s*:\s*([^:\s]+)$/gm;
while (match = pattern.exec(data)) {
result[match[1]] = match[2];
}
return result;
}
var test = parse(list);
// dump array
for (var i in test)
console.log(i + ": " + test[i]);
// select one
console.log(test["driver.parameter.pollinterval"]);
Click here to try it out on jsfiddle

Categories

Resources