Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phát hiện và thay thế tất cả phần tử mảng trong chuỗi bằng RegExp - JavaScript

Giả sử chúng ta có chuỗi sau:

var sentence = "My Name is John Smith. I live in UK. My Favourite Subject is JavaScript."

Chúng ta cần thay thế các từ sau trong câu trên bằng giá trị "Not Available":

var values = ['John', 'Smith', 'UK', 'JavaScript']

Kết quả mong đợi:

My Name is Not Available Not Available. I live in Not Available. My Favourite Subject is Not Available.

Sử dụng biểu thức chính quy để thực hiện.

Ví dụ

Mã minh họa:

var values = ['John', 'Smith', 'UK', 'JavaScript']; 
var sentence = "My Name is John Smith. I live in UK. My Favourite Subject is JavaScript."; 
var regularExpression = new RegExp(values.join('|'), 'gim'); 
sentence = sentence.replace(regularExpression, 'Not Available'); 
console.log(sentence);

Để chạy chương trình, sử dụng lệnh:

node tenFile.js

Tên file ở đây là demo279.js.

Kết quả

Đầu ra trên console:

PS C:\Users\Amit\javascript-code> node demo279.js
My Name is Not Available Not Available. I live in Not Available. My Favourite Subject is Not Available.