-1

How do you use a variable in a regular expression? in this case :

var string = "How are you doing today? You are such a nice person!";
var count =  string.match(/\bare\b/g).length; 
alert(count);// 'are'=>2

Edit my:

var string = "How are you doing today? You are such a nice person!";
var text = 'are';
var count =  string.match(new RegExp('/\b'+text+'\b/g')); 
count = count? count.length : 0;  //checking if there are matches or  not.
alert(count); => Not working
Ba Trần
  • 43
  • 3

1 Answers1

0

Create the regular expression pattern in a variable and then use new RegExp() with that variable that has the pattern. And don't use g as a part of the pattern, pass it as a second argument of RegExp() instead.

var string = "How are you doing today? You are such a nice person!";
var text = 'are';
var regEx = '\\b'+text+'\\b';
var count =  string.match(new RegExp(regEx,"g")).length;
alert(count);
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55
  • Typing in this question's title into a new question automatically links him to all sorts of topics with this answer already, he is just blatantly wasting everyone's time. – ASDFGerte Apr 12 '18 at 14:38
  • @ASDFGerte might be but I think OP is confused because he added `/g` in the first argument instead of second argument in `RegExp` – Ankit Agarwal Apr 12 '18 at 14:39
  • Thanks you very much – Ba Trần Apr 12 '18 at 14:41
  • @TranBa glad to help you – Ankit Agarwal Apr 12 '18 at 14:41
  • 1
    The first suggested duplicate is ["Javascript Regexp dynamic generation from variables?"](https://stackoverflow.com/questions/5090103/javascript-regexp-dynamic-generation-from-variables) (almost identical name) which has an accepted top answer that has `gi` mode. No. Just no. – ASDFGerte Apr 12 '18 at 14:42
  • ```regexp: { regexp : /"^([\w-\.]+)@ domainName"/, message: 'The domain name is wrong and your domain name is: ' + domainName }```. I have regExp like above. Here domainName is variable. I displayed domainName in the message which displayed in GUI. I have read some answer. but I could not make it work since I am new to regExp. @Ankit Agarwal Can you tell me how to pass parameter? – Satheeshkumar Nov 19 '19 at 14:29