Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - How to Globally Replace a Forward Slash in a String?
Next article icon

JavaScript - How to Globally Replace a Forward Slash in a String?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various methods to globally replace a forward slash in the JavaScript string.

1. Using replace() Method with a Regular Expression

The replace() method is commonly used with a regular expression to replace all occurrences of a forward slash.

JavaScript
const s1 = "path/to/some/resource"; const s2 = s1.replace(/\//g, "-");  console.log(s2); 

Output
path-to-some-resource 
  • The /\//g pattern matches all forward slashes.
  • The g flag ensures the replacement is global.

2. Using replaceAll() Method

For modern JavaScript, replaceAll() provides a simpler syntax for replacing all forward slashes without the need for regular expression.

JavaScript
const s1 = "path/to/some/resource"; const s2 = s1.replaceAll("/", "-");  console.log(s2);  

Output
path-to-some-resource 

This method is concise, but it requires ES2021 or later.

3. Using split() and join() Method

An alternative approach involves splitting the string into an array and joining it back with the desired replacement.

JavaScript
const s1 = "path/to/some/resource"; const s2 = s1.split("/").join("-");  console.log(s2);  

Output
path-to-some-resource 

This method is simple and effective for replacing forward slashes globally, especially in older environments where replaceAll() is not supported.

4. Using Array.prototype.map() Method

You can also convert the string to an array, use map() for replacement, and then join it back into a string.

JavaScript
const s1 = "path/to/some/resource"; const s2 = [...s1].map((char) =>  	(char === "/" ? "-" : char)).join("");  console.log(s2);  

Output
path-to-some-resource 

5. Using reduce() Method

The reduce() method can also be used for global replacements.

JavaScript
const s1 = "path/to/some/resource"; const s2 = [...s1].reduce((acc, char) =>  	acc + (char === "/" ? "-" : char), "");  console.log(s2);  

Output
path-to-some-resource 

Which Approach Should You Use?

ApproachWhen to Use

Using replace() with Regex

Best for compatibility and handling patterns or advanced replacements.
Using replaceAll() Ideal for modern JavaScript with clean, readable syntax.
Using split() and join()

Great for environments without replaceAll() or when avoiding regex.

Using a LoopSuitable for educational purposes or custom logic.
Using Array.prototype.map() Useful when you need to transform the string while replacing.

Using reduce()

Best for functional programming scenarios or combining transformations.

While the first three methods (replace(), replaceAll(), and split() + join()) cover most use cases, using functional methods (map() or reduce()) can be helpful in specific situations where additional processing is required.


Next Article
JavaScript - How to Globally Replace a Forward Slash in a String?

S

sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

    How to replace all dots in a string using JavaScript ?
    We will replace all dots in a string using JavaScript. There are multiple approaches to manipulating a string in JavaScript. Table of Content Using JavaScript replace() MethodUsing JavaScript Split() and Join() Method Using JavaSccript reduce() Method and spread operatorUsing JavaScript replaceAll()
    4 min read
    How to get value of a string after last slash in JavaScript?
    The task is to get the string after a specific character('/'). Here are a few of the most used techniques discussed. We are going to use JavaScript. Below are the approaches used to get the value of a string after the last slash in JavaScript: Table of Content Approach 1: Using .split() method and .
    2 min read
    How to Replace All Occurrences of a String in JavaScript?
    Here are different approaches to replace all occurrences of a string in JavaScript.1. Using string.replace() MethodThe string.replace() method is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.Syntaxstr.replace(replac
    2 min read
    How to Add Backslash in JSON String JavaScript ?
    In JavaScript, adding a backslash to a JSON string is important to properly escape special characters, ensuring the integrity and correctness of the JSON format for data processing and storage. Table of Content Using JSON.parse() and JSON.stringify()Using for LoopUsing Array.prototype.map() and Stri
    2 min read
    How to Remove Backslash from JSON String in JavaScript?
    Removing backslash from JSON String is important because it ensures proper JSON formatting for data interchange and prevents syntax errors during parsing, leading to accurate data representation and processing in JavaScript applications. we will going to learn three different approaches to removing
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences