Bạn có thể sử dụng match () với việc chuyển tên biến. Cú pháp như sau -
console.log(yourVariableName.match(yourMatchingVariableName));
Ví dụ
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)); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo107.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo107.js The actual value= My Name is John The matching value= John