Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Joshua Cranmer Newsgroups: comp.lang.java.programmer Subject: Re: Java code to output escaped Javascript? Date: Wed, 01 Jun 2011 10:50:40 -0400 Organization: A noiseless patient Spider Lines: 29 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 1 Jun 2011 14:50:42 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="bAymlyY9SkaJNa8Tz2rerw"; logging-data="21606"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX180oTPwZh69rnlTNn5G2afLu4jkkRXPQWc=" User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.16pre) Gecko/20110305 Lightning/1.0b3pre Thunderbird/3.1.10pre In-Reply-To: Cancel-Lock: sha1:hEY3MUNwSwrPKbG4AjjjO2ArI7w= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:4856 On 06/01/2011 09:11 AM, laredotornado wrote: > Hi, > > I'm using Java 6. I want to output code for a Javascript variable ... > > String jsValue = escapeForJS(value); > String expression = "storedVars['myVar'] = \"" + jsValue + "\";"; > > Is there anything standard that will do this? I came up with my own > function, but I don't want to worry about leaving anything out. Any Java->JSON library worth its salt should be able to do this. > /* creates a JS expression that can be used within quotes. */ > private String escapeForJS(String value) { > value = value.replace("\n", "\\n"); > value = value.replace("\r", "\\r"); > value = value.replace("\"", "\\\""); > return value; > } You also forgot `\' as well as every character in the range '\u0000'-'\u001f' and '\u007f-\uffff' [if you have to worry about non-BMP characters, keep in mind that JS is like Java in that it has the same UCS-2/UTF-16 hairyness]. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth