AntiMuffin AntiMuffin - 3 months ago 14
Javascript Question

Regex - Javascript capture area

I want to capture only a area of the Match part. I have following String:

" type1-class1 type1-class2 type2-class4 type2-type1-class3 "

and i want following result
["class1", "class2"]
.
I am searching the class by the
type
.
I have tried following:



console.log(" type1-class1 type1-class2 type2-class4 type2-type1-class3 ".match(/\btype1-.*?(?= )/g))
// Result: ["type1-class1", "type1-class2", "type1-class3"]





Furthermore i have tried following:



console.log(" type1-class1 type1-class2 type2-class4 type2-type1-class3 ".match(/(?= type1-).*?(?= )/g));
// Result: ["", ""]





How can i disable the capture on the beginning of a Regex?

Answer

I'd use an exec loop. The regular expression is /(?:^|\s)type1-([^ ]+)/g, e.g., "Following a type-1 that's at the beginning of the string or just after whitespace, capture everything until the next whitespace or end of string. (With your string as given, we don't need the alternation with ^, but I wanted to allow for "type1-class1" at beginning of string.) We then collect the captures in a loop:

var rex = /(?:^|\s)type1-([^ ]+)/g;
var str = " type1-class1 type1-class2 type2-class4 type2-type1-class3 ";
var classes = [];
var m;
while ((m = rex.exec(str)) != null) {
  classes.push(m[1]);
}
console.log(classes);

Comments