1

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
1
  • for (...) statement { block } is probably not doing what you expected it to do. Put the statement in the block. Commented Feb 7, 2013 at 17:35

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.