How to parse data in javascript using regex? - javascript

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

Related

Splitting a string between two reoccurring characters

I have dynamic values in a variables, each separated with [ and ] e.g.
var data="[Continuing] [Returning] "; or
var data="[ACCT_BBA] "; or
var data="[12001] [12009] [21077] [13880] ";
var data="[13880] ";
Is there a way to use the split function to extract the values between the [ and the ] from above?
var arr= data.split("<what goes here?>");
e.g. on the last example to retrieve: 12001, 12009, 21077, 13880
data.slice(1, -2).split("] [")
should do the job, or if your start and end are uncertain maybe
data.replace(/^\s*\[|\]\s*$/g, "").split("] [")
Alternatively, if you need something more complex, the choice is usually .match with a global regex, or building your own parser if you need to handle arbitrarily nested structures.
Use
data.split('] [').map(function (item) { return item.replace("]", "").replace("[", "")})
like this:
//var data="[Continuing] [Returning]";
// var data="[ACCT_BBA]";
var data="[12001] [12009] [21077] [13880]";
var res = data.split('] [').map(function (item) { return item.replace("]", "").replace("[", "")})
console.log(res)
What about data.match(/\[(\w+)\]/g).map(e => e.slice(1, -1))
And you can replace \w with the scope of character, like [a-zA-Z0-9_]
Yes if you do:
var data="[12001] [12009] [21077] [13880]";
var arr = data.split(" ");
for(let i = 0; i < arr.length; i++){
arr[i] = arr[i].replace('[','');
arr[i] = arr[i].replace(']','');
}
console.log(arr);
just an example, very basic one.

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);
}
}

Get multiple values from hash in URL

www.domain.com/lookbook.html#look0&product1
On page load I would like to grab the whole hash ie. #look0&product1
then split it up and save the number of the look ie 0 in a variable called var look and the number of the product ie 1 in another variable called var product. Not sure how to achieve this.
Is this also the best way of passing and retrieving such parameters? Thanks
Use var myHash = location.hash to get hash part of URL. Than do var params = myHash.split('&') and after that for each part do part.split('=') to get key-value pairs.
Maybe it's better to pass these parameters via GET from PHP side and than post them inside page when page is processed via PHP?
<input type="hidden" name="look" value="<?php echo isset($_GET['look']) ? $_GET['look'] : '';?>"/>
Here's the pure Javascript method:
function parseHash(hash) {
// Remove the first character (i.e. the prepended "#").
hash = hash.substring(1, hash.length);
// This is where we will store our properties and values.
var hashObj = {};
// Split on the delimiter "&" and for each key/val pair...
hash.split('&').forEach(function(q) {
// Get the property by splitting on all numbers and taking the first entry.
var prop = q.split(/\d/)[0];
// Get the numerical value by splitting on all non-numbers and taking the last entry.
var val_raw = q.split(/[^\d]/);
var val = val_raw[val_raw.length - 1]
// If the property and key are defined, add the key/val pair to our final object.
if (typeof prop !== 'undefined' && typeof val !== 'undefined') {
hashObj[prop] = +val;
}
});
return hashObj;
}
Use like:
parseHash(window.location.hash /* #book10&id1483 */)
/* returns: Object {book: 10, id: 1483} */
I suggest using the norm for passing values through the location's hash: prop=value. Ex: #book=10&id=311. Then you can easily split on = for each property.
You can use .match(re) method with use of regular expression to extract the number from the given string.
You can try this:
var hashes = location.hash.split('&'); // get the hash and split it to make array
var values = hashes.map(function(hash){ // use .map to iterate and get a new array
return hash.match(/\d+/)[0]; // returns the numbers from the string.
});
var loc = "look0345345345&product1";
var hashes = loc.split('&');
var values = hashes.map(function(hash){ return hash.match(/\d+/)[0]; });
document.body.innerHTML = '<pre>'+ JSON.stringify(values) + '</pre>';
You could try this:
var url = 'www.domain.com/lookbook.html#look0&product1'
, result = {}
, expr = RegExp(/[#&]([a-zA-z]+)(\d+)/g);
var parts = expr.exec(url);
while(parts != null && parts.length == 3) {
result[parts[1]] = parts[2];
parts = expr.exec(url);
}
var look = result['look']
, product = result['product'];
document.getElementById('result').innerHTML = 'look = ' + look + '<br>' + 'product = ' + product;
<p id='result'></p>
We are basically using a regular expression to divide the parameter name and value into two groups that we can then get by calling expr.exec(url).
Each time we call expr.exec(url), we get the next set of name and value groups.
We set the value of the parameter to its name in the result object.
In the regular expression /[#&]([a-zA-z]+)(\d+)/g, the g after the /.../ means match each time find the two groups.
The two groups are prefaced by either & or # ([#&]). The first group is a String of letters ([a-zA-z]+), the name of the parameter. The second is a String of numbers (\d+), the value you are looking for.
The regex returns the String that matches the pattern as the first result in the parts array, followed by the groups matched, which which means that our two groups in each iteration will be parts[1] and parts[2].
you should use:
function parseHash(hash){
hash = hash.substring(1, hash.length); //remove first character (#)
var obj ={}; //create the output
var qa = hash.split('&'); //split all parameters in an array
for(var i = 0; i < qa.length; i++){
var fra1 = qa[i].split('='); //split every parameter into [parameter, value]
var prop = fra1[0];
var value = fra1[1];
if(/[0-9]/.test(value) && !isNaN(value)){ //check if is a number
value = parseInt(value);
}
obj[prop] = value; //add the parameter to the value
}
return obj;
}
document.querySelector("input.hash").onkeyup = function(){
console.log( parseHash(document.querySelector("input.hash").value));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="hash"/>
<p class="output"></p>
use as
parseHash(location.hash /* #look=0&product=1 );
/returns {look: 0, product: 1}/

How to check an input words against several arrays in 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

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.

Categories

Resources