Problem
We are required to write a JavaScript function that takes in a string and replaces all appearances of dots(.) in it with dashes(-).
input
const str = 'this.is.an.example.string';
Output
const output = 'this-is-an-example-string';
All appearances of dots(.) in string str are replaced with dash(-)
Example
Following is the code −
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));Code Explanation
We iterated through the string str and checked if the current element is a dot, we added a dash in the res string otherwise we added the current element.
Output
this-is-an-example-string