Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Replacing dots with dashes in a string using JavaScript
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';
Expected Output
const output = 'this-is-an-example-string';
All appearances of dots(.) in string str are replaced with dash(-)
Method 1: Using replace() with Regular Expression
The most efficient approach is using the built-in replace() method with a global regular expression:
const str = 'this.is.an.example.string';
const replaceDots = (str = '') => {
return str.replace(/\./g, '-');
};
console.log(replaceDots(str));
this-is-an-example-string
Method 2: Using split() and join()
Another clean approach is splitting the string by dots and joining with dashes:
const str = 'this.is.an.example.string';
const replaceDots = (str = '') => {
return str.split('.').join('-');
};
console.log(replaceDots(str));
this-is-an-example-string
Method 3: Using Manual Loop
For educational purposes, here's a manual iteration approach:
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));
this-is-an-example-string
Performance Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
replace(/\./g, '-') |
Fastest | High | Production code |
split('.').join('-') |
Good | Highest | Simple replacements |
| Manual loop | Slowest | Low | Learning purposes |
Handling Edge Cases
const replaceDots = (str = '') => {
return str.replace(/\./g, '-');
};
// Test edge cases
console.log(replaceDots('')); // Empty string
console.log(replaceDots('no-dots')); // No dots
console.log(replaceDots('...')); // Only dots
console.log(replaceDots('.start.end.')); // Dots at boundaries
no-dots --- -start-end-
Conclusion
Use str.replace(/\./g, '-') for the best performance and readability. The split().join() method is also clean and intuitive for simple character replacements.
Advertisements
