0

I need to replace all backslashes in a string with another symbol. I use regex for that, but it just doesn't work

const name = 'AC\DC'; 
const replaced = icon.replace(/\\/g, "-");

console.log(name);
console.log(replaced);

// ACDC
// ACDC

For example, in this string the backslash is not replaced and not even shown when I log the origial string in a console.

I get such strings from external source so I can't escape the backslash or use another character.

b3rry
  • 21
  • 5
  • Because there's no backslash in `name`. Your replace method works as it is when the string (`icon`!) actually contains a backslash. – Teemu May 03 '23 at 04:47

2 Answers2

1

When you have backslash character in a string, it is used to escape next character. Just like how you use to escape the backslash in your regex. To correctly test this, you should do use name like this:

const name = "AC\\DC";

console.log(name);
console.log(name.replace(/\\/g, "-"));
Vincent
  • 872
  • 1
  • 7
  • 13
0

You need to change the first line to "AC\\DC" as follows since "" is an escape character, you will never get a "" in console.log(name).

const name = 'AC\\DC'; 
const replaced = name.replace(/\\/g, "-");

console.log(name);
console.log(replaced);