Build key/value Object from slash-separated URL - javascript

Given a slash separated URL like http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3 how could I build a key/value Object with the dynamic parameters (param1/value, param2/value2...) of this URL?
Valid parameters always have this slash separated paramand value format and some/fixed/path would be a substring manually provided.
I tried to split the full URL (or whatever it could be) by the fixed substring and I managed to slice the dynamic params out of it as I wanted but I couldn't create the key/value Object as I needed:
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
url.split( uri ).forEach(function(x){
var arr = x.split('/');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log( result );
But this piece of code only brings me the first pair instead of all of them and it requires the uri to obligatorily have a trailing slash. If the substring doesn't have it or has one to the left it acts all weird with a blank key and the first key as value o.O
I know it's simple, but I just can't do it. I tried to search but this must have a very specific way to refer to because I couldn't find by my own.
One last thing, if you don't mind explain instead of just give me the fish, I'd appreciate, so there won't have a next time... hopefully

You were only taking the second part after some/fixed/path/. You need to split this second part and iterates over the array. On each even index, I create a new property in the object with the name of the previous element
x is the current element
i is the current index
a is the array containing each element after splitting with /
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
var paramsToSplit = url.split(uri)[1];
paramsToSplit.split('/').forEach((x,i,a)=>{
if(i%2)
result[a[i-1]] = x;
});
console.log( result );

Try this:
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var url = url.substring(url.indexOf(uri) + uri.length)
var options = url.split('/');
var results = [];
for(var i=0;i<options.length; i+=2){
results.push({[options[i]]:options[i+1]})
}

Are you looking for somethig like that?
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var params = [];
var values = [];
var results = {};
url.split( uri )[1].split('/').forEach(function(e,i) {
if(i%2==0){
params.push(e)
} else {
values.push(e);
}
})
console.log( params, values );
params.forEach(function(e,i) {
results[e] = values[i];
});
console.log( results );

You may do as follows;
var text = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
result = text.split("/")
.slice(6)
.reduce((r,c,i,a) => i&1 ? Object.assign(r,{[a[i-1]]: c}) : r, {});
console.log(result);

You are quite close, you basically need to make another for loop for your produced arr and step every 2 values. Like so...
var url = "http://www.example.com/some/fixed/path/param1/value1/param2/value2/param3/value3";
var uri = "some/fixed/path/";
var result = {};
url.split( uri ).forEach(function(x){
var arr = x.split('/');
var step;
for (step = 0; step <= arr.length; step += 2) {
arr[step + 1] && (result[arr[step]] = arr[step + 1]);
}
});
console.log( result );

Related

Splitting string on first equals sign in javascript

I am trying to use Javascript to split some data out of a url The url looks along the lines of....
var1=green&var2=yellow&newUrl=[url.php?id=2]
I am managing to split the url by the '&' signs to give me one array of three items. I am then trying to split this array by the first '=' sign to give me a list of fields and variables. Its working fine until it hits the second = sign within the newUrl field. Any ideas of how I can split this string at the first '=' sign.
my code so far is...
var href = $(this).attr("href");
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
var str = vars[i].split("=");
alert(str[0] +':' +str[1]);
}
}
my results are
var1:green var2:yellow var3:[url.php?id
Any ideas?
**Edit to show my final code based on Wand Maker's solution **
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
alert(str[0] +':' +str[1].substring(1);
}
Try something like below for splitting around =
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
You could use join() for the third element in the array as below:
var lst = href.split("&");
var var1 = href[0].split("=")[1];
var var2 = href[1].split("=")[1];
var var3 = href[2].split("=").slice(1,2).join("");
function splitFirstInstance(str,item){
var res = [];
var found = true;
res.push("");
for (var i = 0; i < str.length;i++){
if (str[i] === item && found === true){
res.push("");
found = false;
} else {
res[res.length-1] += str[i];
}
}
return res;
}
splitstr("I Want to Split First a","a"); // ["I W","nt to Split First a"]

Select 2 characters after a particular substring in javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.
.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle
I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know
indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);
Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.
There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

Split url into tab in javascript

input:
"/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
javascript:
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
var parts = parmeters.split('[&=]');
output of my js code:
0: "passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
length: 1
i want to split my url into a map with key:value like this
output:
origin:THR
destination:TDR
goDate:2015-01-09
passengers:STANDARD:1
returnDate:2015-01-10
max:0
withThac:false
My code not do exactly what i want in output, what is wrong ?
You should split with
var params = parmeters.split('&')
and then split all the values you get
for (var i = 0,len = params.length; i<len;i++){
var data = params[i].split("=", 2); // Max 2 elements
var key = data[0];
var value = data[1];
...
}
i think your wrong ' characters
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
/*--> i think used regexp. Clear ' Char. --> */var parts = parmeters.split(/[&=]/);
use this like..
good luck
A possible solution using ECMA5 methods and assuming that your string is always the same pattern.
var src = '/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false',
slice = src.split(/[\/|?|&]/).slice(3),
data = slice.reduce(function (output, item) {
var split = item.split('=');
output[split.shift()] = split.shift();
return output;
}, {
origin: slice.shift(),
destination: slice.shift(),
goDate: slice.shift()
});
document.body.appendChild(document.createTextNode(JSON.stringify(data)));

How to get parameter value inside a string?

Here's a thing i've been trying to resolve...
We've got some data from an ajax call and the result data is between other stuff a huge string with key:value data. For example:
"2R=OK|2M=2 row(s) found|V1=1,2|"
Is it posible for js to do something like:
var value = someFunction(str, param);
so if i search for "V1" parameter it will return "1,2"
I got this running on Sql server no sweat, but i'm struggling with js to parse the string.
So far i'm able to do this by a VERY rudimentary for loop like this:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
var arr = str.split("|");
var i = 0;
var value = "";
for(i = 0; i<arr.length; ++i){
if( arr[i].indexOf(param)>-1 ){
value = arr[i].split("=")[1];
}
}
console.log(value);
if i put that into a function it works, but i wonder if there's a more efficient way to do it, maybe some regex? but i suck at it. Hopefully somebody may shine a light on this for me?
Thanks!
This seems to work for your specific use-case:
function getValueByKey(haystack, needle) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp(needle + '=(.+)');
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1');
console.log(test);
JS Fiddle demo.
And, to include the separator in your search (in order to prevent somethingElseV1 matching for V1):
function getValueByKey(haystack, needle, separator) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp('\\' + separator + needle + '=(.+)\\' + separator);
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1', '|');
console.log(test);
JS Fiddle demo.
Note that this approach does require the use of the new RegExp() constructor (rather than creating a regex-literal using /.../) in order to pass variables into the regular expression.
Similarly, because we're using a string to create the regular expression within the constructor, we need to double-escape characters that require escaping (escaping first within the string and then escaping within in the created RegExp).
References:
RegExp.
String.match().
This should work for you and it's delimiters are configurable (if you wish to parse a similar string with different delimiters, you can just pass in the delimiters as arguments):
var parseKeyValue = (function(){
return function(str, search, keyDelim, valueDelim){
keyDelim = quote(keyDelim || '|');
valueDelim = quote(valueDelim || '=');
var regexp = new RegExp('(?:^|' + keyDelim + ')' + quote(search) + valueDelim + '(.*?)(?:' + keyDelim + '|$)');
var result = regexp.exec(str);
if(result && result.length > 1)
return result[1];
};
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
})();
Quote function borrowed form this answer
Usage examples:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
parseKeyValue(str, param); // "1,2"
var str = "2R=OK&2M=2 row(s) found&V1=1,2";
var param = "2R";
parseKeyValue(str, param, '&'); // "OK"
var str =
"2R=>OK\n\
2M->2 row(s) found\n\
V1->1,2";
var param = "2M";
parseKeyValue(str, param, '\n', '->'); // "2 row(s) found"
Here is another approach:
HTML:
<div id="2R"></div>
<div id="2M"></div>
<div id="V1"></div>
Javascript:
function createDictionary(input) {
var splittedInput = input.split(/[=|]/),
kvpCount = Math.floor(splittedInput.length / 2),
i, key, value,
dictionary = {};
for (i = 0; i < kvpCount; i += 1) {
key = splittedInput[i * 2];
value = splittedInput[i * 2 + 1];
dictionary[key] = value;
}
return dictionary;
}
var input = "2R=OK|2M=2 row(s) found|V1=1,2|",
dictionary = createDictionary(input),
div2R = document.getElementById("2R"),
div2M = document.getElementById("2M"),
divV1 = document.getElementById("V1");
div2R.innerHTML = dictionary["2R"];
div2M.innerHTML = dictionary["2M"];
divV1.innerHTML = dictionary["V1"];
Result:
OK
2 row(s) found
1,2

Javascript Split Array and assign values to variables from NZBMatrix API

Not sure if any of you guys/girls out there that uses the NZBMatrix website API..
In short what I'm trying to do is build an Adobe Air Application,
using JavaScript, AJAX to connect to the API with a search query, this is all good.
When i receive the "request.responseText" back from the API with the 5 results
(can only be 5) I'm having trouble with the JavaScript split function trying to split them all out...
the return string is returned as follows:
NZBID:444027;
NZBNAME:test result 1;
LINK:nzbmatrix.com/nzb-details.php?id=444027&hit=1;
SIZE:1469988208.64;
INDEX_DATE:2009-02-14 09:08:55;
USENET_DATE:2009-02-12 2:48:47;
CATEGORY:TV > Divx/Xvid;
GROUP:alt.binaries.test;
COMMENTS:0;
HITS:174;
NFO:yes;
REGION:0;
|
NZBID:444028;
NZBNAME:another test;
LINK:nzbmatrix.com/nzb-details.php?id=444028&hit=1;
SIZE:1469988208.64; = Size in bytes
etc..etc..
the first Array should split each set of results using |
assign those 5 results to a new array.
the 2nd Array should split each value using :
assign those 12 results to new variables
ie: var nzbidtxt = array1[0]; which would echo like:
document.write(nzbidtxt); // ie: print "NZBID:"
the 3rd Array should split each variable from ;
assign those 12 values to the newly created array
ie: var nzbidValue = array2[0]; which would echo like:
document.write(nzbValue); // ie: print "444027"
so using both arrays I can display a listing of the posts returned..
in a nice usable format..
nzbid: 444027 // this will be used for direct download
nzbName: the name of the nzb
etc..etc..
the function i have been working on is below:
function breakNzbUrlResponse(text)
{
var place = new Array;
var place2 =new Array;
var place3 =new Array;
place[0] = text.indexOf('|');
place2[0] = text.indexOf(':');
place3[0] = text.indexOf(';');
var i = 1;
while(place[i-1] > 0 || i==1) {
place[i] = text.indexOf('|',place[i-1]+1);
place2[i] = text.indexOf(':',place2[i-1]+1);
if(place2[i] == -1)
{
place2[i] = text.length;
}
i++;
}
i=1;
var vars = new Array;
var values = new Array;
var retarray = new Array;
vars[0] = text.substr(0,place[0]);
values[0] = text.substr((place[0]+1),((place2[0]-place[0])-1));
retarray[vars[0]] = values[0];
while(i < (place.length-1) || i==1)
{
vars[i] = text.substr((place2[i-1]+1),((place[i]-place2[i-1])-1));
values[i] = text.substr((place[i]+1),((place2[i]-place[i])-1));
//alert('in loop\r\nvars['+i+'] is: '+vars[i]+'\r\nvalues['+i+'] is: '+values[i]);
retarray[vars[i]] = values[i];
i++;
}
return retarray;
}
This feels and looks like a very long winded process for this type..
all I want to do is basically assign a new variable to each return type
ie
var nzbid = array3[0];
which when split would reference the first line of the return string, NZBID:444027; where the value for NZBID would be 44027..
bit of a book going on, but the more info the better i suppose.
Thanks
Marty
You could probably cut out a significant number of lines of code by further utilizing split() instead of the manual dissections of the entries and using multidimensional arrays instead of repeatedly creating new arrays.
The logic would be:
ResultsArray = split by "|"
FieldArray = Each element of FieldArray split by ";"
ValueArray = Each element of FieldArray split by ":"
2 years later, it's sad that NZBMatrix is still using this horrible format. Here is how you can parse it.
//used to hold temporary key/value pairs
var tempKV = {};
//used to hold the search results
this.searchResults = [];
//The unformatted search results arrive in inResponse
//Remove whitespace and newlines from the input
inResponse = inResponse.replace(/(\r\n|\n|\r)/gm,"");
//search entries are delimited by |
var results = inResponse.split("|");
for(var i = 0; i < results.length; i++){
//key:value pairs in each search result are dlimited by ;
var pair = results[i].split(";");
for(var j = 0; j < pair.length; j++){
//keys and values are delimited by :
var kv = pair[j].split(":");
//normal key:value pairs have a length of 2
if(kv.length == 2){
//make sure these are treated as strings
//tempKV["key"] = "value"
tempKV["" + kv[0]] = "" + kv[1];
}
//Else we are parsing an entry like "http://" where there are multiple :'s
else if(kv.length > 2){
//store the first chunk of the value
var val = "" + kv[1];
//loop through remaining chunks of the value
for(var z = 2; z < kv.length; z++){
//append ':' plus the next value chunk
val += ":" + kv[z];
}
//store the key and the constructed value
tempKV["" + kv[0]] = val;
}
}
//add the final tempKV array to the searchResults object so long
//as it seems to be valid and has the NZBNAME field
if(tempKV.NZBNAME){
this.searchResults[i] = tempKV;
}
//reset the temporary key:value array
tempKV = {};
}
//all done, this.searchResults contains the json search results

Categories

Resources