Constructing a URL from an array - javascript

I have an Array:
var arr[];
I have inserted many coordinates to this (x and y values)
arr[0]=12+'#'+32;
arr[1]=34+'#'+87;
arr[2]=90+'#'+89;
So when i print this array i get a string like ,12#32,34#87,90#89. These are coordinates. How do i break these and append this to a string which will be in the format.
http://host/app?x1=12&y1=32&x2=32&y2=87&x3=90&y3=89
This above URL can have many parameters. How can i construct the above URL from my array.

You can build your querystring looping through the array (here I used .each()) and using the .split() function to separate your coordinates.
var qs;
$.each(arr,function(i,v){
qs += "x" + i + "=" + v.split("#")[0] + "&y" + i + "=" + v.split("#")[1] + ((i+1)!=arr.length) ? "&" : "";
});
var url = "http://host/app?" + qs;

Similar to the above answers, loop through, split on the hash, add the pieces to the query string, and append the ampersand if you're not at the end.
for(var c = 0, query = "http://host/app?", coordinate; c < arr.length; c++) {
coordinate = arr[c].split("#");
query += "x" + (c + 1) + "=" + coordinate[0] + "&";
query += "y" + (c + 1) + "=" + coordinate[1];
if(c < arr.length - 1) query += "&";
}

The simplest approach I can think of is:
var arr = [12+'#'+32, 34+'#'+87, 90+'#'+89],
url = 'http://host/app',
params = [], temp;
arr.forEach(function (a) {
temp = a.split('#');
params.push('x=' + temp[0] + 'y=' + temp[1]);
});
url += params.join('&');
console.log(url);
var arr = [12+'#'+32, 34+'#'+87, 90+'#'+89],
url = 'http://host/app',
params = [], temp;
arr.forEach(function (a) {
temp = a.split('#');
params.push('x=' + temp[0] + 'y=' + temp[1]);
});
url += params.join('&');
console.log(url);
References:
Array.prototype.forEach().
Array.prototype.join().
Array.prototype.push().
String.prototype.split().

Related

Javascript How to add array with another array into a new array?

So my challenge right now is unable to add array with another array into another new array.
my code:
var disabletimerange = { basedonservicetype: "", basedonservicer: "" }
var arr = [{"StartTime":"09:00:00","EndTime":"09:10:00"},{"StartTime":"10:00:00","EndTime":"15:00:00"}]
for (var xx = 0; xx < arr.length; xx++) {
var bookedStartTime, bookedEndTime
bookedStartTime = arr[xx].StartTime.slice(0, -3)
bookedEndTime = arr[xx].EndTime.slice(0, -3)
if (disabletimerange.basedonservicer === "") {
var disabletimealreadybookedtiming = "[" + '"' + bookedStartTime + '"' + "," + '"' + bookedEndTime + '"' + "]"
disabletimerange.basedonservicer = JSON.parse(disabletimealreadybookedtiming)
} else {
var disabletimealreadybookedtiming = "[" + '"' + bookedStartTime + '"' + "," + '"' + bookedEndTime + '"' + "]"
disabletimerange.basedonservicer = "[" + "[" + disabletimerange.basedonservicer + "]" + "," + disabletimealreadybookedtiming + "]"
disabletimerange.basedonservicer = JSON.parse(disabletimerange.basedonservicer)
}
Uncaught SyntaxError: Unexpected number in JSON at position 3 --> at the last line it cannot parse.
In short, what i want is basically 2 array stick tgt instead of adding into it
var y = ["hi", "123"]
var x = ["yo", "312"]
this
[["hi", "123"], ["yo", "312"]] instead of ["hi", "123", "yo", "312"]
and it must be array. not text form
You can do:
var y = ["hi", "123"]
var x = ["yo", "312"]
var result = [x, y]
console.log(result)
As you described
How to add array with another array into a new array?
create a new array
push your arrays into this new array one by one
let x = [1,2];
let y = [3.4];
let z = [];
z.push(x)
z.push(y);
console.log(z);

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);

Returning a String instead of looping print statement

I'm new to Javascript and I'm curious as to how to store values in a string and then return it. In the example below 2 numbers are picked, for example 2 and 8, and the program should return 2x1 =2, 2x2=4,..... all the way up to 2x8 =16. This can obviously be done by constantly looping a print statement as I have done, but how would I be able to store all the values in a String and then return the string.
function showMultiples (num, numMultiples)
{
for (i = 1; i < numMultiples; i++)
{
var result = num*i;
console.log(num + " x " + i + " = " + result+ "\n");
}
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2,8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3,2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5,4));
function showMultiples(num, numMultiples) {
// the accumulator (should be initialized to empty string)
var str = "";
for (i = 1; i < numMultiples; i++) {
var result = num * i;
// use += to append to str instead of overriding it
str += num + " x " + i + " = " + result + "\n";
}
// return the result str
return str;
}
var mulOf5 = showMultiples(5, 10);
console.log("multiples of 5 are:\n" + mulOf5);
The operator += add the a value (right operand) to the previous value of the left operand and stores the result in the later. So these two lines are the same:
str = str + someValue;
str += someValue;
You could just use string concatenation:
var finalResult = ""
...in your loop...
finalResult += num + " x " + i + " = " + result+ "\n"
Often you can also just collect the results in an array and use join to append them.
var lines = [];
... in your loop:
lines.push(num + " x " + i + " = " + result);
... afterwards
console.log(lines.join("\n"));
In case you wanted to use ES6 syntax using backticks for a template string, you can use the below. This is a little more readable and is exactly where it is useful (so long as you can use ES6 wherever you're using JavaScript).
function showMultiples(num, numMultiples){
let result = '';
for(let i = 1; i < numMultiples; i++){
result += `${num} x ${i} = ${i * num}\n`;
};
return result;
}
console.log(showMultiples(2,8));

Replace everything between two strings with numbers i++ {0},{1}

Have mechanism that replaces strings like .NET string.Format in javascript ("{0} - {1}",'a','b') would result "a - b".
I am looking for mechanism that would Replace everything between two strings with {0}{1}...
Example :
var str = "([OrderDate] >= Func:{TheApplication().GetProfileAttr('TestDate')} ) and [OrderDate] < 1/1/2013 AND [Name] = Func:{TheApplication().GetProfileAttr('Name')}"
stringFormatProducer(str,"Func:{","}");
would give result
"([OrderDate] >= {0} ) and [OrderDate] < 1/1/2013 AND [Name] = {1}"
I have this mechanism done in horrid way where I am splitting it on Func:{ then } then iterating over it, I am sure someone already has a better solution.
var i = 0;
str.replace(/Func:{[^}]+}/g, function(c) {
return '{' + i++ + '}';
});
Or more flexible way:
var i = 0,
func = 'Func:';
str.replace(new RegExp(func + '{[^}]+}', 'g'), function(c) {
return '{' + i++ + '}';
});
A complete method for you:
String.prototype.createFormattingString = function(prefix, open, close) {
var re = new RegExp(prefix + open + '[^' + close + ']+' + close, 'g'),
i = 0;
return this.replace(re, function(c) {
return '{' + i++ + '}';
});
};
'(VAR > Func:{ some text })'.createFormattingString('Func:', '{', '}');
'(VAR > Func:[ some text ])'.createFormattingString('Func:', '\\[', '\\]');

How to use join (in built method) in javascript?

In javascript loop i am generating a xml like this:
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
//s = s.join(' ');
}
Forgot about the t variable and all. by run this code i am getting the s value in the following format:
<row dc = "abc" al="56" msg="dkaj" />
In the second iteration it shows like this:
<row dc = "abwwc" al="56w" msg="dkajad" />
and so on till the m<t.length satisfy. What i want to join the list in each iteration. After joining all of them i should get in this way:
<row dc = "abc" al="56" msg="dkaj" /><row dc = "abwwc" al="56w" msg="dkajad" /> and so on..
I tried to do it with join written in comment section, but didn't work for me. What i am doing wrong?
The best way would be to define a string outside the loop an append to it;
var v = '';
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
v += s;
}
alert(v);
If you still want to use join(), make v an array and push() elements on to it (note that join() is an array method, not for string's)
var y = [];
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
y.push(s);
}
alert(y.join(''));
You'll be pleased to see I've tried to adhere to your variable naming conventions in my examples (i.e. meaningless characters).

Categories

Resources