使用 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 次浏览

开启你的 职业

完成课程即可获得认证

开始学习
广告
© . All rights reserved.