TheRealPapa
TheRealPapa

Reputation: 4539

Javascript find all "\" and replace with "/"

I am stuck doing this. I am working with a CMS built in ASP.net and it generates image sources using \ for folder path. I need to read this src and use it somewhere else as a background image to a div, which requires / for path separators.

Tried these without success:

str.replace(new RegExp('\', 'g'), '/');
str.replace(/\/g), '/');

Thanks

Upvotes: 0

Views: 75

Answers (3)

Madi Naf
Madi Naf

Reputation: 665

Try with this

 var str = "assets\imges\img.jpg";
 var res = str.replace(/\\/g, "/");

Upvotes: 1

Bibberty
Bibberty

Reputation: 4768

A different approach I suppose.

let str = `\\test\\string\\h.html`;
console.log(str);

str = str.split('\\').join('/');
console.log(str);

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816252

\ is the escape character in string and regular expression literals. To produce a literal \ you have to escape it itself:

console.log(
  "\\path\\to\\file".replace(/\\/g, '/')
  //                          ^^
);

Upvotes: 5

Related Questions