Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery extract words from string

Tags:

jquery

string

I have a simple question. Using jQuery I want to extract words in a string to an arrary. How do I do this? Any examples?

e.g. If I have a string as shown below: I want to get only the words with the '@' prefix

var accts = "@userA @userB @userC   @userD invalidUserE @userF ";

Thanks, K.R.

like image 339
user686924 Avatar asked Aug 30 '26 02:08

user686924


2 Answers

You don't really need jQuery, you can do this quite simply with basic JavaScript:

var accts = "@userA @userB @userC   @userD invalidUserE @userF ";
var split = accts.split(" ");
for(var i = 0; i < split.length; i++) {
    if(split[i].charAt(0) == "@") {
      //Got one
    } 
}

You can do whatever you want to do with the strings as you find each one. You should also be able to use a regular expression.

like image 117
James Allardice Avatar answered Aug 31 '26 18:08

James Allardice


Since you asked for jquery

var result = $.grep(accts.split(" "), function(a){ return /^@/.test(a) } )

Gives you:

["@userA", "@userB", "@userC", "@userD", "@userF"]
like image 33
dave Avatar answered Aug 31 '26 18:08

dave