Replace forward slash "/ " character in JavaScript string?

Javascript

Javascript Problem Overview


I have this string:

var someString = "23/03/2012";

and want to replace all the "/" with "-".

I tried to do this:

someString.replace(///g, "-");

But it seems you cant have a forward slash / in there.

Javascript Solutions


Solution 1 - Javascript

You need to escape your slash.

/\//g

Solution 2 - Javascript

Try escaping the slash: someString.replace(/\//g, "-");

By the way - / is a (forward-)slash; \ is a backslash.

Solution 3 - Javascript

First of all, that's a forward slash. And no, you can't have any in regexes unless you escape them. To escape them, put a backslash (\) in front of it.

someString.replace(/\//g, "-");

Live example

Solution 4 - Javascript

Escape it: someString.replace(/\//g, "-");

Solution 5 - Javascript

Just use the split - join approach:

my_string.split('/').join('replace_with_this')

Solution 6 - Javascript

You can just replace like this,

 var someString = "23/03/2012";
 someString.replace(/\//g, "-");

It works for me..

Solution 7 - Javascript

Remove all forward slash occurrences with blank char in Javascript.

modelData = modelData.replace(/\//g, '');

Solution 8 - Javascript

The option that is not listed in the answers is using replaceAll:

 var someString = "23/03/2012";
 var newString = someString.replaceAll("/", "-");

Solution 9 - Javascript

Area.replace(new RegExp(/\//g), '-') replaces multiple forward slashes (/) with -

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMo.View Question on Stackoverflow
Solution 1 - JavascriptChris SobolewskiView Answer on Stackoverflow
Solution 2 - JavascriptChowlettView Answer on Stackoverflow
Solution 3 - JavascriptAlex TurpinView Answer on Stackoverflow
Solution 4 - JavascriptSuprView Answer on Stackoverflow
Solution 5 - JavascriptCyberneticView Answer on Stackoverflow
Solution 6 - JavascriptPrabhagaranView Answer on Stackoverflow
Solution 7 - JavascriptArifMustafaView Answer on Stackoverflow
Solution 8 - JavascriptbarnskiView Answer on Stackoverflow
Solution 9 - Javascriptharitha chittaView Answer on Stackoverflow