skip to Main Content

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 = 'ACDC'; 
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.

2

Answers


  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, "-"));
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search