Tạo đối tượng RegExp từ chuỗi biến để dùng trong match(), replace(), test().
Ví dụ
var sentence = 'My Name is John';
var searchWord = 'John';
// Tạo RegExp từ biến, flag 'g' = global
var regex = new RegExp(searchWord, 'g');
console.log("Chuỗi:", sentence);
console.log("Từ khóa:", searchWord);
console.log("Kết quả match:", sentence.match(regex));
Cách chạy
node demo.js
Kết quả
Chuỗi: My Name is John
Từ khóa: John
Kết quả match: [ 'John' ]
Lưu ý: Nếu biến chứa ký tự đặc biệt regex (.*+?^${}()|[]\\), cần escape trước:
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var regex = new RegExp(escapeRegExp(searchWord), 'g');