I’m writing a utility that takes in a .resx file and creates a javascript object containing properties for all the name/value pairs in the .resx file. This is all well and good, until one of the values in the .resx is
This dealer accepts electronic orders.
/r/nClick to order {0} from this dealer.
I’m adding the name/value pairs to the js object like this:
streamWriter.Write(string.Format("\n{0} : \"{1}\"", kvp.Key, kvp.Value));
When kvp.Value = “This dealer accepts electronic orders./r/nClick to order {0} from this dealer.”
This causes StreamWriter.Write() to actually place a newline in between ‘orders.’ and ‘Click’, which naturally screws up my javascript output.
I’ve tried different things with @ and without using string.Format, but I’ve had no luck. Any suggestions?
Edit: This application is run during build to get some javascript files deployed later, so at no point is it accessible to / run by anyone but the app developers. So while I obviously need a way to escape characters here, XSS as such is not really a concern.
Your problem has already happened by the time you get to this code. String.Format will not “expand” literal
\nand\rin the substituted strings ({0}etc) into newline and CR, so it must have happened at some earlier point, possibly while reading the .resx file.You have two possible solutions. One, as you discovered in the comments to DonaldRay’s answer, is to explicitly reverse this replacement, and replace literal newlines with the two characters
\n:You will need to do the same for every character that could appear in your strings. \n and \r are the most common, and then \t (tab); that’s probably enough for most dev tools.
Alternatively, you could look upstream at the .resx file reading code, and try to find and remove the part that’s explicitly expanding these character sequences. This would be a better general solution, if it’s possible.