0

For a message in a specific message format (HL7) I'm trying to escape the ^ sign. So the string abc^def^ghi should become abc\^def\^ghi

I tried the following ways:

> "abc^def^ghi".replace("^", "\^");
'abc^def^ghi'
> "abc^def^ghi".replace("^", "\\^");
'abc\\^def^ghi'
> "abc^def^ghi".replace("^", "\\\^");
'abc\\^def^ghi'
> "abc^def^ghi".replace("\^", "\\\^");
'abc\\^def^ghi'
> "abc^def^ghi".replace("\\^", "\\\^");
'abc^def^ghi'
> "abc^def^ghi".replace(/^/g, "\\\^");
'\\^abc^def^ghi'
> "abc^def^ghi".replace(/\^/g, "\\\^");
'abc\\^def\\^ghi'
> "abc^def^ghi".replace(/\^/g, "\\^");
'abc\\^def\\^ghi'
> "abc^def^ghi".replace(/\^/g, "\^");
'abc^def^ghi'
> "abc^def^ghi".replace(/\\^/g, "\\\^");
'abc^def^ghi'

As you can see, none of them work as I want them to. Does anybody know how I can do this?

kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

2
"abc^def^ghi".replace(/\^/g, "\\\^")

You have to escape ^ in the regex, because it's a special character.

Andy Ray
  • 30,372
  • 14
  • 101
  • 138