Easy way to extract substring in Javascript

I am 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 achieve this? One liner, preferably?

+5
source share
4 answers

Should there be a category \bbefore a category?
You can shorten it by putting an empty array if the match is not fulfilled;

 category = (classProp.match(/category_[a-z]+\b/) || [""])[0];
+7
source

Well, this is already very close to single line. You can simplify the if block to the following:

if(match){
  category = match[0];
}
0
source

:

try { var category = 'active category_games'.match(/category_[a-z]+\b/).pop(); } catch(e) {}
0

:

var category = (classProp.match(/category_[a-z]+\b/) || "")[0] || undefined;

@ziesemer.

0

All Articles