
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- How to replace all dots in a string using JavaScript?
- Replacing vowels with their 1-based index in a string in JavaScript
- Replacing upperCase and LowerCase in a string - JavaScript
- Replacing all special characters with their ASCII value in a string - JavaScript
- Replacing every nth instance of characters in a string - JavaScript
- Replacing spaces with underscores in JavaScript?
- Replacing zero starting with whitespace in JavaScript
- Replacing Substrings in a Java String
- Replacing digits to form binary using JavaScript
- JavaScript: replacing object keys with an array
- JavaScript Strings: Replacing i with 1 and o with 0
- Sort items in MySQL with dots?
- Replacing space with a hyphen in C++
- Update a column value, replacing part of a string in MySQL?
- Replacing words with asterisks in C++

Advertisements