Javascript replace forward slashes in a string: Forward slashes can be replaced in Javascript by using replace()
method or split() & join()
methods.
Replace using regular expressions: The Javascript string replace()
function accepts either a string parameter or a regular expression. We can use this function and pass the global modifier (g)
to replace all the occurrences of a character or a string to replace. Because (/) forward slash is a special character, we need to escape it using (\)
Example of Forward slash using regular expression:
var text = "1/1/2020"; var result = text.replace(/\//g,'-');
This will return:
1-1-2020
Example:
<html> <head> <title>Javascript String forward Slash example</title> </head> <body> <p id="demo"></p> <button onclick="replaceSlash()">Replace Slash</button> <p id="result"></p> <script> var text = "1/1/2020"; var demo = document.getElementById("demo"); var result = document.getElementById("result"); demo.innerHTML = text; function replaceSlash() { result.innerHTML = text.replace(/\//g,'-'); } </script> </body> </html>
Output:
Using split()
and join()
method to replace Slashes in Javascript string: The javascript split()
method splits a string into an array. After splitting the string object, we can join it using a required character or a string value.
Example:
var text = "1/1/2020"; var result = text.split('/').join('-');
Result:
1-1-2020
Example:
<html> <head> <title>Javascript String forward Slash example</title> </head> <body style="font-family:Arial;font-size:20px;"> <p id="demo"></p> <button onclick="replaceSlash()">Replace Slash</button> <p id="result"></p> <script> var text = "1/1/2020"; var demo = document.getElementById("demo"); var result = document.getElementById("result"); demo.innerHTML = text; function replaceSlash() { result.innerHTML = text.split('/').join('-'); } </script> </body> </html>
Output will be same as previous example:
Also see:
How to filter array in Javascript?
Sorting Array objects in Javascript
Creating a minimal design clock using only Javascript
Getting current Date and Time using Javascript
Showing notifications using JQuery and Javascript.