從字串中刪除所有空格 - JavaScript


我們需要編寫一個 JavaScript 函式,該函式接收一個字串並返回一個新字串,其中包含原始字串的所有字元,只是刪除了空格。

示例

讓我們編寫此函式的程式碼 -

const str = "This is an example string from which all whitespaces will be
removed";
const removeWhitespaces = str => {
   let newStr = '';
   for(let i = 0; i < str.length; i++){
      if(str[i] !== " "){
         newStr += str[i];
      }else{
         newStr += '';
      };
   };
   return newStr;
};
console.log(removeWhitespaces(str));

輸出

刪除空格後控制檯中的輸出 -

Thisisanexamplestringfromwhichallwhitespaceswillberemoved

更新:2020-09-15

188 瀏覽數

啟動你的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.