Computer >> Máy Tính >  >> Lập trình >> Javascript

Thay thế dấu phẩy bằng JavaScript Regex?

Giả sử sau đây là các chuỗi có dấu phẩy của chúng ta -

"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 thay thế và trong đó, sử dụng Biểu thức chính quy. Sau đâ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(ma
   kingRegularExpression, " JavaScript"));
}

Để 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à demo164.js.

Đầu ra

Điều này sẽ tạo ra kết quả sau -

PS C:\Users\Amit\javascript-code> node demo164.js
My Favorite subject is, ==== replaced by JavaScript ==== My Favorite sub
ject is JavaScript
My Favorite subject is, and teacher name is Adam Smith ==== replaced by
JavaScript ==== My Favorite subject is JavaScript and teacher name is Ad
am Smith
My Favorite subject is, and got the marks 89 ==== replaced by JavaScript
==== My Favorite subject is JavaScript and got the marks 89