Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to extract a substring in Javascript

I'm trying to extract a substring matching a given pattern from a string in Javascript. Example:

var classProp = 'active category_games',
    match = classProp.match(/category_[a-z]+\b/),
    category;
if(match !== null && match.length > 0){
  category = match[0];
}

Is there an easier way to acheive this? A one-liner, preferably?

like image 642
Jørgen Avatar asked Dec 06 '11 11:12

Jørgen


1 Answers

Should there be a \b before category?
You could shorten it by supplying an empty array if the match fails;

 category = (classProp.match(/category_[a-z]+\b/) || [""])[0];
like image 99
Alex K. Avatar answered Sep 24 '22 19:09

Alex K.