使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP