How to put variable in regular expression match with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 09-Sep-2020 16:27:42
Advertisements