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(","))
asked Feb 7, 2013 at 17:34
ofumbi
3731 gold badge4 silver badges11 bronze badges
2 Answers 2
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"
});
answered Feb 7, 2013 at 17:39
Alex K.
177k32 gold badges276 silver badges299 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Feb 7, 2013 at 17:36
Leeish
5,2132 gold badges20 silver badges48 bronze badges
Comments
lang-js
for (...) statement { block }is probably not doing what you expected it to do. Put the statement in the block.