I have a loop that is generating a string
function jsonResponse(response)
{
var singleString = a + "," + b + "," + c + "|";
}
with console.log(singleString);
I see them all generated :
a1,b1,c1|
a2,b2,c2|
a3,b3,c3|
But how can I create a new variable allStrings
that will concatenate all of these into one string? The loop is part of an ajax response that is looping through xml nodes to retrieve the data for those variables. I guess I need to make them part of an array and then join them back together for one big string?
To further clarify what I am trying to achieve is something like :
var allStrings = singleString[0] + singleString[1] + singleString[2] ;
a1,b1,c1|a2,b2,c2|a3,b3,c3|
To better explain the loop it looks like this :
$j.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function parseXml(data)
{
$j('.loader').fadeOut();
itemQueue = $j(data).find("ITEM").map( function ()
{
return {
date: $j("LAST_SCAN" , this).text(),
type : $j("PRODUCT_TYPE", this).text(),
cat : $j("CLASS_NAME", this).text(),
};
}).get();
getNextItem();
}
});
function getNextItem()
{
var item = itemQueue[0];
var singleString = item.date+ "," + item.type + "," + item.cat + "\n";
console.log( singleString );
$j.ajax({
url: s7query,
dataType: 'jsonp'
});
}
function s7jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
// run other processes when finished with checks
if (!itemQueue.length)
{
// alert ("ALL DONE");
}
}
you should use the join() function, it will concatenate the strings and insert the selected character inside the (), for example: originalStr. join('-') will result in "yesterday-i-go-to-school", but you can absolutely use empty spaces like join(' ').
To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
The “+” operator with a String acts as a concatenation operator. Whenever you add a String value to a double using the “+” operator, both values are concatenated resulting a String object. In-fact adding a double value to String is the easiest way to convert a double value to Strings.
You can use Array.join
to convert an array to a string.
Example:
var arr = ['a1', 'b1', 'c1'];
console.log(arr.join(',')); // 'a1,b1,c1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With