77

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.

1
  • helpful for pass the parameters to the query string so like decoding then encode them in destination page querystring Commented Oct 18, 2017 at 11:42

9 Answers 9

137

You need to escape your slash.

/\//g
Sign up to request clarification or add additional context in comments.

Comments

40

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

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

Comments

22

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

Comments

5

Just use the split - join approach:

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

Comments

4

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

Comments

4

Remove all forward slash occurrences with blank char in Javascript.

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

Comments

3

You can just replace like this,

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

It works for me..

Comments

2

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

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.