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

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
ToTa
  • 3,304
  • 2
  • 19
  • 39
  • 2
    It's been asked and asnwered less than an hour ago: http://stackoverflow.com/questions/18865402/replace-with-in-javascript – pawel Sep 18 '13 at 07:34
  • possible duplicate of [Replacing all occurrences of a string in javascript?](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – Imran Jawaid Sep 18 '13 at 07:58
  • It's not duplicate, my problem is far away from that one. – ToTa Sep 18 '13 at 08: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 `\ `. – pawel Sep 18 '13 at 08:08

5 Answers5

2

Try regular expressions with the global (g) flag.

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

var replaced = str.replace(regex, '/');
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
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.

Community
  • 1
  • 1
pawel
  • 35,827
  • 7
  • 56
  • 53
  • You won't get to the single `\ ` in `"stack\overflow"`, because it's disregarded by JS interpreter as soon as it parses that string. – pawel Sep 18 '13 at 08:01
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, "/");
Akshaya Shanbhogue
  • 1,438
  • 1
  • 13
  • 25
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

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
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");

Community
  • 1
  • 1
sathya
  • 1,404
  • 2
  • 15
  • 26