ToTa
ToTa

Reputation: 3334

.replace() function doesn't replace forward slash with backslash

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

Upvotes: 0

Views: 3759

Answers (5)

sathya
sathya

Reputation: 1424

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");

Upvotes: 0

pawel
pawel

Reputation: 36965

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.

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16764

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

Upvotes: 0

Akshaya Shanbhogue
Akshaya Shanbhogue

Reputation: 1448

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, "/");

Upvotes: 0

Joe Simmons
Joe Simmons

Reputation: 1838

Try regular expressions with the global (g) flag.

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

var replaced = str.replace(regex, '/');

Upvotes: 2

Related Questions