如何在 Javascript 中分割空格分隔的字串並移除多餘的逗號和空格?


假設我們的字串如下:-

var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";

使用正則表示式以及 split() 和 join() 來去除多餘的空格和逗號。以下是程式碼:-

示例

var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";
console.log("Before removing extra comma and space="+sentence);
sentence = sentence.split(/[\s,]+/).join();
console.log("After removing extra comma and space=");
console.log(sentence)

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

node fileName.js.

輸出

這裡,我的檔名是 demo133.js。這將產生以下輸出:-

PS C:\Users\Amit\JavaScript-code> node demo133.js
Before removing extra comma and space=My,,,,,,, Name,,,, is John ,,, Smith
After removing extra comma and space=
My,Name,is,John,Smith

更新於: 11-Sep-2020

332 次瀏覽

開始你的 職業生涯

完成課程並獲得認證

開始
廣告