用 JavaScript 正則表示式替換逗號?


假設以下字串帶有逗號 −

"My Favorite subject is,"
"My Favorite subject is, and teacher name is Adam Smith"
"My Favorite subject is, and got the marks 89"

若要替換逗號,請使用 replace,並在其中使用正則表示式。下面是該程式碼 −

示例

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"));
}

若要執行上述程式,你需要使用以下命令 −

node fileName.js.

這裡,我的檔名是 demo164.js。

輸出

這將產生如下輸出 −

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

更新時間: 2020 年 9 月 12 日

599 次瀏覽

啟動你的 事業

透過完成該課程獲取認證

開始
廣告
© . All rights reserved.