GigaPudding
GigaPudding

Reputation: 45

regex match begining using variable

So i want this correct match() syntax with variable var a = 'breaksmooth'; and var b = 'bre'; , what i knew if i'm not using any variable or at least search in variable : if(a.match(/^bre/)) return true; i just want to achieve this if(a.match(/^b/); where b is var b which is give me error .i dont want to change var b with b = /^bre/. any solution ?

Upvotes: 1

Views: 44

Answers (2)

melpomene
melpomene

Reputation: 85787

If you just want to check whether a starts with b, you don't need a regex at all:

var a = 'breaksmooth';
var b = 'bre';
if (a.startsWith(b)) {
    console.log('yes');
}

See the startsWith method.

On the other hand, if you want to create a regex from a string, you can use the RegExp constructor:

var b = 'bre';
var regex = new RegExp('^' + b);  // same as /^bre/

You don't even need a separate variable:

if (a.match(new RegExp('^' + b))) {

Upvotes: 0

Rishab
Rishab

Reputation: 1532

Use this method:

var a = 'breaksmooth';
var b = 'bre';
var re = new RegExp(b, 'g');
a.match(re)

Upvotes: 1

Related Questions