Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Create an array from a delimited string and then evaluate its values

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 !

like image 692
matteo Avatar asked Nov 28 '22 01:11

matteo


2 Answers

var theString = "B01, B20, B03, ";

$.each(theString.split(",").slice(0,-1), function(index, item) {
    alert(item); 
});

Let me know if you have any questions.

like image 133
Jon Hinson Avatar answered Feb 16 '23 01:02

Jon Hinson


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]);
  }
}
like image 45
Guffa Avatar answered Feb 16 '23 01:02

Guffa