3

I am trying to replace certain characters with other certain characters using one .replace()

eg. I would like to replace

\u0026 with &

and

\u0027 with '

depending on which is needed to be replaced.

  • 2
    No. You will need multiple `replace` calls. – luk2302 May 17 '19 at 14:51
  • 2
    But why you can't cal .replace() two times with different inputs? Or can you extend your question with some code and more precise context? – Eugene May 17 '19 at 14:51
  • To those asking why not call `.replace()` twice: Imagine you are replacing a string that contains 1 billion characters. You really don't want to call `replace()` twice as that would create an intermediate 2-gigabyte object when it can be avoided by coding it differently. – DodgyCodeException May 17 '19 at 15:40
  • See [Alternative to successive String.replace](https://stackoverflow.com/questions/26735276/alternative-to-successive-string-replace) – DodgyCodeException May 17 '19 at 16:30

1 Answers1

1

You need to have multiple .replace calls because you want to replace specific items with other specific items

If you wanted to replace any instance of \u0027 or \u0026 with just one character then you could use a single replace.

However, to achieve what you want, then you need something like this:

str.replace("\u0027","'").replace("\u0026","&")
  • Better approach would be `return str.replace("\u0027","'").replace("\u0026","&")`. No need to use `contains`. – mukesh210 May 17 '19 at 15:04