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 ?
Asked
Active
Viewed 40 times
1

GigaPudding
- 45
- 8
-
3Possible duplicate of [Use dynamic (variable) string as regex pattern in JavaScript](https://stackoverflow.com/questions/17885855/use-dynamic-variable-string-as-regex-pattern-in-javascript) – helloitsjoe Jul 20 '19 at 13:51
2 Answers
1
Use this method:
var a = 'breaksmooth';
var b = 'bre';
var re = new RegExp(b, 'g');
a.match(re)

Rishab
- 1,484
- 2
- 11
- 22
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))) {

melpomene
- 84,125
- 8
- 85
- 148