- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replacing dots with dashes in a string using JavaScript
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
Advertisements
To Continue Learning Please Login
Login with Google