greatTeacherOnizuka
greatTeacherOnizuka

Reputation: 565

Regex to get all JS class names in an array

I am trying to write a simple regex that matches all class names in a file. It should match them either with or without a space before the curly bracket.

E.g.

class myClass {...}

Returns ['myClass']

class myClass {....} class Foo{...}

Returns ['myClass', 'foo'].

And so on.

This is what I have so far but it doesnt seem to be working when there is no space befor ethe bracket:

([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\{)

Upvotes: 0

Views: 64

Answers (2)

Taki
Taki

Reputation: 17654

Use positive lookbehind and lookahead :

const str = 'class myClass {....} class Foo{...} class Bar   { /* this is a class comment */ }';

const result = str.match(/(?<=class\s)(\w+)(?=\s*{)/g);

console.log(result)

Upvotes: 3

Igor Bykov
Igor Bykov

Reputation: 2822

If you want to get not only class declarations but also class instances you might use something like (considering class names follow convention & start from a capital letter):

const sample = `class Foo {};
$a = new Bar;

const myConst = 42;

function thisIsAFunction(){
    console.log(123);
}

class FlowController{}

let laser = new LaserActivator()

var myVar;class NewClass{...};
`;

const classExp = /[\s;][A-Z]\w+?[({\s;]/gm;

sample.match(classExp); //[" Foo ", " Bar;", " FlowController{", " LaserActivator(", " NewClass{"]

Or if you don't want additional characters like spaces, semicolons, etc. to be present, you could use lookahead (something like this):

/[\s;][A-Z]\w+?(?=([\({\s]))/gm;

Upvotes: 0

Related Questions