-1

I am trying to handle backslash so that I am able to convert \t(single) to \t (double \) but this code /regex doesn't work. Could you help me with where I am doing it wrong?

var a = {"value": '[{"skill":"\tAgile,Scrum", "exp": 2}, {"skill": "Coding", "exp": 10 }]'};


a.value = a.value.replace(/\\/g, "\\\\"); //handle special char

console.log(a);
art
  • 226
  • 3
  • 11
  • 30

2 Answers2

1

Your string doesn't have any literal backslashes in it. For example, \tAgile,Scrum is equivalent to a tab character concatenated with Agile,Scrum. There are no backslashes in the string, so /\\/g, which matches a literal backslash, will not match anything.

You'll have to match the interpreted character(s) instead, like \t, and replace them with a literal backslash followed by a literal t:

var a = {"value": '[{"skill":"\tAgile,Scrum", "exp": 2}, {"skill": "Coding", "exp": 10 }]'};

a.value = a.value.replace(/\t/g, "\\t"); //handle special char

console.log(a);

You'll have to write out each character you want to replace. If you have a bunch of them (eg \t \r \n \v etc) you might find it more concise to start with an object mapping the characters to their replacement values and constructing the pattern from that, eg:

const replacements = {
  '\t': '\\t',
  '\r': '\\r',
  // etc
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Because the \t has already been parsed and handled as a \t character (a tabletop I believe). Look for a \t:

var a = {
  "value": '[{"skill":"\tAgile,Scrum", "exp": 2}, {"skill": "Coding", "exp": 10 }]'
};

a.value = a.value.replace(/\t/g, "\\t"); //handle special char

console.log(a);

Or you could use a backticked string:

var a = {
  "value": `[{"skill":"\tAgile,Scrum", "exp": 2}, {"skill": "Coding", "exp": 10 }]`
};

console.log(a);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79