3

Ok. This may be a dumb question but I am stuck.

In my javascript, I have a string variable that contains ' which stands for single quote. e.g. some_text_'_some_text Now, I want to replace this with the actual single quote like some_text_'_some_text.

Obvious way would be using str.replace(/'/g,"'") but the problem is I write this javascript code into a third party software that replaces ' by ' when I save the script. So, if I open script again, it shows str.replace(/'/g,"'"). So when the script runs, it does not do replace operation correctly.

One would ask why do I need this replace to work?
The reason is that this variable is passed on to build a SQL query and I don't want ' in my query. I want it to be ' instead which I can escape in SQL.

EDIT
So, I realized the reason for this behavior and potential answerers may want to take this into account. The software I work with stores all its files as XML including javascript code I write. So, it converts all special characters to HTML codes while saving and parses them back when it reads it. That's the reason ' gets converted to '.

tumchaaditya
  • 1,267
  • 7
  • 19
  • 49
  • You need to decode your html entities. Take a look at this answer :) http://stackoverflow.com/questions/5796718/html-entity-decode – dev7 Feb 04 '14 at 00:39
  • Also - you can do it easier on most server side scripting. i.e with PHP you can use `htmlspecialchars_decode` and then escape it. – dev7 Feb 04 '14 at 00:41
  • 2
    `str.replace(/'/g,"'")`? – Bergi Feb 04 '14 at 00:47
  • 1
    And if @Bergi’s suggestion doesn’t help, try to trick the software by something like `str.replace(new RegExp("&"+"#"+"x27;", "g"), "'")` … try recognizing _that_ as numeric character reference, you sneaky little 3rd party party-crasher software! – CBroe Feb 04 '14 at 02:45
  • @Bergi: For some reason, it didn't work. You may want to post it as answer in case someone has same problem in future and your answer works for him/her. And thanks for the help. – tumchaaditya Feb 04 '14 at 18:03
  • @CBroe: This worked. Can you post it as answer so that I can mark it accepted? – tumchaaditya Feb 04 '14 at 18:04

1 Answers1

6

If @Bergi’s suggestion doesn’t help, try to trick the software by something like

str.replace(new RegExp("&"+"#"+"x27;", "g"), "'")

– basically splitting the numeric character reference into several pieces, so that the software that is messing with things can’t recognize it as such any more.

CBroe
  • 91,630
  • 14
  • 92
  • 150
  • This worked for me. Although for someone else with similar problem, @Bergi 's answer may work as well. – tumchaaditya Feb 04 '14 at 18:10
  • Still needed this answer for me. For ref, this issue is basically like https://stackoverflow.com/questions/8482949/jquery-autocomplete-result-shows-encoded-characters but with the ' apostrophe character from (previously) XML data loading via JSON – TimDC May 27 '20 at 23:02