Reputation: 373
I want to extract only groups from this string
I want to have something like in alert "group1,group2" but it returns empty.
var phone_nos = "group1,group2,564774890900";
var recipients = phone_nos.split(",");
for( var i=0; i<recipients.length; i++ )
group =recipients[i].substring(0,5)
{ if (group=="group")
{groups.push(recipients)}
}
alert(groups.join(","))
Upvotes: 1
Views: 58
Reputation: 175986
Some misplaced braces for the for
and assuming you want to filter group*
you need to add recipients[i]
the groups
array rather than the original recipients
string.
var phone_nos = "group1,group2,564774890900";
var recipients = phone_nos.split(",");
var groups = [];
for (var i=0; i < recipients.length; i++) {
group = recipients[i].substring(0,5);
if (group == "group") {
groups.push(recipients[i]);
}
}
alert(groups.join(","))
Modern browsers/IE9+
var groups = phone_nos.split(",").filter(function(v) {
return v.substring(0, 5) === "group"
});
Upvotes: 2
Reputation: 5213
You have an error of sorts.
for( var i=0; i<recipients.length; i++ ){
group =recipients[i].substring(0,5)
if (group=="group")
{groups.push(recipients)}
}
You for statement was only running the next line of code, not the block I think. If you format your code better you will be better able to see errors like this.
for( var i=0; i<recipients.length; i++ )
group =recipients[i].substring(0,5)
// MORE CODE
This above only runs the first complete line after the for.
Upvotes: 2