1

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 ?

1

2 Answers 2

1

Use this method:

var a = 'breaksmooth';
var b = 'bre';
var re = new RegExp(b, 'g');
a.match(re)
Sign up to request clarification or add additional context in comments.

2 Comments

g flag is for global match.
And what do you mean by "global match"?
0

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))) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.