使用 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