0

I want to change all slashes into one string and I can't find solution. This is my code:

var str = 'some\stack\overflow', 
replacement = '/';
var replaced = str.replace("\", "/");
console.log(replaced);
console.log("I want to see this: some/stack/overflow");

Jsfiddle

4
  • 2
    It's been asked and asnwered less than an hour ago: stackoverflow.com/questions/18865402/replace-with-in-javascript Commented Sep 18, 2013 at 7:34
  • possible duplicate of Replacing all occurrences of a string in javascript? Commented Sep 18, 2013 at 7:58
  • It's not duplicate, my problem is far away from that one. Commented Sep 18, 2013 at 8:00
  • It's phrased like your problem was "str.replace only replaces the first occurrence" (which is part of your problem), while the hard part is replacing single unescaped \ . Commented Sep 18, 2013 at 8:08

5 Answers 5

2

Try regular expressions with the global (g) flag.

var str = 'some\\stack\\overflow';
var regex = /\\/g;

var replaced = str.replace(regex, '/');
Sign up to request clarification or add additional context in comments.

Comments

0
var str = 'some\\stack\overflow'

^^ This is incorrect. Corrected string is-

var str = 'some\\stack\\overflow'

Also, use global regular expression.

var replaced = str.replace(/\\/g, "/");

Comments

0

Well,

your str contains only one \\ group, you try to replace only \\ so is normally to see something like some/stackoverflow, so your code is :

var str = 'some\\stack\overflow' // your code 

and str must be

var str = 'some\\stack\\overflow'

then will works

Comments

0

Other than using regex to replace every occurrence, not just the first one as described here (So, use str.replace(/\\/g, "/");)

You need to fix your string before passing it to JavaScript.

"some\stack\overflow" will be interpreted as "somestackoverflow". "\s" and "\o" are treated as escape sequences, not "slash letter", so the string doesn't really have any slashes. You need "some\\stack\\overflow". Why? that's why:

"s\tackoverflow" == "s    ackoverflow"

"stackove\rflow" == "stackove
flow"

"\s" and "\o" just happen to not mean anything special.

1 Comment

You won't get to the single \ in "stack\overflow", because it's disregarded by JS interpreter as soon as it parses that string.
0

Try Some Thing like this:

var str = 'some\stack\overflow';

replacement = '/';

replaced = str.replace("\", "/");

console.log(replaced);

console.log("I want to see this: some/stack/overflow");

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.