i've this problem i'm not really able to solve.
i have this string "B01, B20, B03, "
i would like to create a jQuery array off this string using the "," as delimiter then remove the last element ( that would be blank ) and then for each value of the array make an alert.
Something like...
var theString = "B01, B20, B03, ";
var theArray = (theString, ',');
theArray = remove_last_element; (??)
$('theArray').each(function() {
alert(theArray[?].value);
});
Any hint ?
Thanks !
var theString = "B01, B20, B03, ";
$.each(theString.split(",").slice(0,-1), function(index, item) {
alert(item);
});
Let me know if you have any questions.
There is no such thing as a "jQuery array". You use a Javascript array.
You can't just turn a string into an array because it contains comma separated values. You have to use something to parse the string, which would be the split
method in this case:
var theString = "B01, B20, B03, ";
var theArray = theString.split(", ");
This produces an array with four items, as there is a trailing separator, so you can check for that and remove it:
if (theArray.length > 0 && theArray[theArray.length - 1].length == 0) {
theArray.pop();
}
Then you can either use plain Javascript or a jQuery method to loop the array. The plain Javascript looks like this:
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
Using a jQuery method looks like this:
$.each(theArray, function(index, item) {
alert(item);
});
You can also skip the step of removing the item, and just check for empty items in the loop:
var theString = "B01, B20, B03, ";
var theArray = theString.split(", ");
for (var i = 0; i < theArray.length; i++) {
if (theArray[i].length > 0) {
alert(theArray[i]);
}
}
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