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
  • 45,059
  • 106
  • 285
  • 459

1 Answers1

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

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

Andy Ray
  • 28,150
  • 13
  • 92
  • 132