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
Inverting slashes in a string in JavaScript
When working with strings in JavaScript, you may need to replace forward slashes (/) with backslashes (\) or vice versa. This is common when dealing with file paths or URL manipulation.
This article demonstrates how to create a function that takes a string containing forward slashes and converts them to backslashes.
Problem Statement
We need to write a JavaScript function that:
- Takes a string that may contain forward slashes (
/) - Returns a new string with all forward slashes replaced by backslashes (
\)
Method 1: Using a for Loop
Here's a solution using a traditional for loop to iterate through each character:
const str = 'Th/s str/ng /conta/ns some/ forward slas/hes';
const invertSlashes = str => {
let res = '';
for(let i = 0; i
Th\s str\ng \conta\ns some\ forward slas\hes
Method 2: Using replace() Method
A more concise approach uses the built-in replace() method with a regular expression:
const str = 'Th/s str/ng /conta/ns some/ forward slas/hes';
const invertSlashes = str => {
return str.replace(/\//g, '\');
};
console.log(invertSlashes(str));
Th\s str\ng \conta\ns some\ forward slas\hes
Method 3: Using split() and join()
Another approach splits the string by forward slashes and joins with backslashes:
const str = 'Th/s str/ng /conta/ns some/ forward slas/hes';
const invertSlashes = str => {
return str.split('/').join('\');
};
console.log(invertSlashes(str));
Th\s str\ng \conta\ns some\ forward slas\hes
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
| for Loop | Good | Moderate | Learning/complex logic |
| replace() | Excellent | High | Simple replacements |
| split()/join() | Good | High | Single character replacement |
Conclusion
The replace() method with regex is the most efficient and readable approach for inverting slashes. Use the for loop method when you need more complex character processing logic.
