Giả sử sau là các chuỗi của chúng ta có dấu phẩy:
"My Favorite subject is," "My Favorite subject is, and teacher name is Adam Smith" "My Favorite subject is, and got the marks 89"
Để thay thế dấu phẩy, hãy sử dụng replace và trong đó, sử dụng Biểu thức chính quy. Dưới đây là mã:
Ví dụ
const makingRegularExpression = /,(?=[^,]*$)/;
replaceComma("My Favorite subject is,");
replaceComma("My Favorite subject is, and teacher name is Adam Smith");
replaceComma("My Favorite subject is, and got the marks 89");
function replaceComma(values) {
console.log(values, " ==== replaced by JavaScript ==== ", values.replace(makingRegularExpression, " JavaScript"));
}
Để chạy chương trình trên, bạn cần sử dụng lệnh sau:
node fileName.js
Tên tệp của tôi là demo164.js.
Kết quả
Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\javascript-code> node demo164.js My Favorite subject is, ==== replaced by JavaScript ==== My Favorite subject is JavaScript My Favorite subject is, and teacher name is Adam Smith ==== replaced by JavaScript ==== My Favorite subject is JavaScript and teacher name is Adam Smith My Favorite subject is, and got the marks 89 ==== replaced by JavaScript ==== My Favorite subject is JavaScript and got the marks 89