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 ?
-
3Possible duplicate of Use dynamic (variable) string as regex pattern in JavaScripthelloitsjoe– helloitsjoe2019-07-20 13:51:22 +00:00Commented Jul 20, 2019 at 13:51
Add a comment
|
2 Answers
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))) {