开发者

Properly format a Java String to fit into a JavaScript variable

I'm pretty new to Java, let's say I have a String containing multiple things (quotes, double quotes, new lines etc...)

I want to "encode" that string so I can output it safely into a JavaScript snippet like:

var test = '<%= myJavaString %>';

So if there's any special characters into myJavaString like newlines, ex:

String myJavaString = "hello\neveryone\nof the\nworld";

I don't want my JavaScript source to look like:

var test = 'hello
everyone
of the
world';

Any built-in functions!?

Th开发者_开发问答anks!


Look at Apache commons-lang StringEscapeUtils class. It has a escapeEcmaScript method which will escape the newline chars to \n, but also the tab, quote and double-quote chars.


Well, I'm not sure if there are any built-in methods you can use, but it probably wouldn't be too hard to write one. Remember, you just need to replace \n with \\n to change it from a "special" character into just a \ and an n.

You may want to use regular expressions. Sadly, I'm not the best at regular expressions, so I may not be the best person to help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜