Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ใส่ตัวแปรใน Regular Expression Match ด้วย JavaScript

ใช้ new RegExp(variable, 'flags') สร้าง Regex จากตัวแปร แล้วใช้ match()

ตัวอย่างโค้ด

var sentence = 'My Name is John';
console.log("The actual value=");
console.log(sentence);

var matchWord = 'John';
console.log("The matching value=");
console.log(matchWord);

var matchRegularExpression = new RegExp(matchWord, 'g');
console.log(sentence.match(matchRegularExpression));

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo107.js)

ผลลัพธ์

The actual value= My Name is John
The matching value= John
[ 'John' ]

คำเตือน: ต้อง Escape ตัวอักษรพิเศษในตัวแปรด้วย escapeRegExp ก่อนสร้าง RegExp