用於移除逗號和逗號後單詞的 JavaScript 正則表示式?


假設我們有以下字串 -

var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);

我們必須刪除逗號和逗號後單詞後面的文字,即刪除“我住在美國”並保留其餘部分。這將成為結果字串 -

My Name is John, Smith

為此,我們將 match() 與 split() 結合使用。

示例

var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);
var expression = sentence.match(/([^,]*)(.*)/)[1];
var positionForComma = sentence.match(/([^,]*),(.*)/)[2].split(' ')[1]
var newValue = expression + ', ' + positionForComma
console.log("Updated="+newValue);

要執行上述程式,您需要使用以下命令 -

node fileName.js.

在此,我的檔名是 demo175.js。

輸出

這將生成以下輸出 -

PS C:\Users\Amit\javascript-code> node demo175.js
The original value=My Name is John, Smith I live in US
Updated=My Name is John, Smith

更新於: 12-9-2020

559 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.