用逗號分隔句子並去掉前後空白 - JavaScript?


假設以下內容是帶有逗號和空白的字串 −

var sentences = "  John ,    David ,         Bob ,      Mike,            Carol        ";

要按逗號分割句子,請使用 split()。要刪除周圍的空格,請使用 trim()。

示例

程式碼如下 −

var sentences = "  John , David , Bob , Mike, Carol ";
console.log("The value=" + sentences);
var result = sentences.split(",").map(function (value) {
   return value.trim();
});
console.log("After modifying the value=")
console.log(result);

要執行以上程式,請使用以下命令 −

node fileName.js.

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

輸出

輸出如下 −

PS C:\Users\Amit\javascript-code> node demo235.js
The value=  John ,    David ,         Bob ,      Mike,            Carol        
After modifying the value=
[ 'John', 'David', 'Bob', 'Mike', 'Carol' ]

更新於:03-Oct-2020

7K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.