0

I have a requirement where I want to replace all occurrences of ',' with '\,'. It works if I try to replace with other characters/strings, but seems to have some issue with '\,'.

'http://example.com/pqr?xyz=11,22.html'.replace(/,/g, '\,')

I expect to get result as 'http://example.com/pqr?xyz=11\,22.html'.

Thanks in advance !!

EDIT

After trying couple of answers (use '\\,' instead of '\,'), I found that console.log is escaping \ i.e it is showing single slash instead of double slash. When I use this variable, it is considering double slash value.

I am seeing two different results when I use console log vs not using console.log.

enter image description here

Shivam Kubde
  • 545
  • 1
  • 8
  • 17
  • 2
    In regex, the '\' char is used to escape other chars to make them literal. to make this char literal you need to escape it as well. `\\,`. – Gil May 12 '21 at 07:40
  • I don't know your use case, but "\" isn't a valid URL character unless it's properly encoded. See this [post](https://stackoverflow.com/questions/7109143/what-characters-are-valid-in-a-url). – Drew Reese May 12 '21 at 08:10
  • @DrewReese Yeah.. I know adding "\" will make it invalid URL, but I want to consider it as string. Actually my intention here is to escape comma, so to do that I wanted to add '\' before comma. I used URL in the example, but that will not always be use case. – Shivam Kubde May 12 '21 at 08:27

2 Answers2

0

Will this be good enough? you need to escape the \

console.log('http://example.com/pqr?xyz=11,22.html'.replace(/,/g, '\\,'))
Someone Special
  • 12,479
  • 7
  • 45
  • 76
  • console.log is printing the expected result, but when I tried it by assigning it to a variable and found that it is producing result with \\ (double slash) - "http://example.com/pqr?xyz=11\\,22.html" – Shivam Kubde May 12 '21 at 07:48
0

let url ="http://example.com/pqr?xyz=11,22.html"
url = url.replace(',' , '\\,')
console.log(url)
Krutik Raut
  • 139
  • 7
  • console.log is printing the expected result, but when I tried it by assigning it to a variable and found that it is producing result with \\ (double slash) - "example.com/pqr?xyz=11\\,22.html" – Shivam Kubde May 12 '21 at 08:39