使用 JavaScript 替換字串中句點為破折號


問題

我們需要編寫一個 JavaScript 函式,該函式以字串為輸入,並用破折號 (-) 替換字串中出現的所有句點 (.)。

輸入

const str = 'this.is.an.example.string';

輸出

const output = 'this-is-an-example-string';

字串 str 中出現的所有句點 (.) 都用破折號 (-) 替換了

示例

以下是程式碼 −

 即時演示

const str = 'this.is.an.example.string';
const replaceDots = (str = '') => {
   let res = "";
   const { length: len } = str;
   for (let i = 0; i < len; i++) {
      const el = str[i];
      if(el === '.'){
         res += '-';
      }else{
         res += el;
      };
   };
   return res;
};
console.log(replaceDots(str));

程式碼說明

我們遍歷字串 str,並檢查當前元素是否為句點,如果是,我們在 res 字串中新增破折號,否則我們添加當前元素。

輸出

this-is-an-example-string

更新日期: 2021 年 4 月 17 日

403 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始學習
廣告