Syntax error How to put variable in regular expression match with JavaScript?

How to put variable in regular expression match with JavaScript?



You can use match() with passing the variable name. The syntax is as follows −

console.log(yourVariableName.match(yourMatchingVariableName));

Example

var senetence = 'My Name is John';
console.log("The actual value=");
console.log(senetence);
var matchWord = 'John';
console.log("The matching value=");
console.log(matchWord);
var matchRegularExpression = new RegExp(matchWord, 'g' );
console.log(senetence.match(matchWord));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo107.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo107.js
The actual value=
My Name is John
The matching value=
John
Updated on: 2020-09-09T12:57:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements