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?

3
  • 3
    You already have it "abc^def^ghi".replace(/\^/g, "\\^"); but showing incorrect output. Commented Jul 12, 2017 at 17:02
  • 1
    Which REPL did you use for this test? Commented Jul 12, 2017 at 17:05
  • 1
    @anubhava! I used the node repl in the terminal, but I now see it does give the right output in the Chromium console. Thanks for pointing this out! Commented Jul 12, 2017 at 17:08

1 Answer 1

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

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.