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: Travers Naran Newsgroups: comp.lang.java.programmer Subject: Re: Java code to output escaped Javascript? Date: Wed, 01 Jun 2011 07:47:26 -0700 Organization: A noiseless patient Spider Lines: 23 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:47:28 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="Nn+8F4uXfbtTJsVfLDMW5A"; logging-data="20392"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+buvCSok/8f96BieMMuoid" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.17) Gecko/20110414 Lightning/1.0b2 Thunderbird/3.1.10 In-Reply-To: Cancel-Lock: sha1:QCGZfdShdgohG62fB8C9w9Jyuo8= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:4855 > 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. > > /* 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; > } That's how I would do it, but if you want existing code, maybe you can adapt something from this library: http://www.json.org/java/ Specifically, this class: http://www.json.org/javadoc/org/json/JSONWriter.html