1

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!?

Thanks!

5
  • Just a note: the appearance of the rendered javascript source is really immaterial - if your string has newlines and you want the newlines passed to javascript, that is what it will look like. Who's going to be looking at your rendered source? Rendered javascript is about function, not form. Just sayin' Commented Aug 26, 2011 at 16:12
  • 3
    @Chris - Actually, it does matter. Javascript doesn't handle multi-line strings properly, unless you add a forward slash to the end of each line. Commented Aug 26, 2011 at 16:15
  • Theres no built-in functions for what your looking for. Which inevitably leads to the next question, is there sample code out there already that does the same thing. Commented Aug 26, 2011 at 16:20
  • @Chris/Sam Dufel: Also, all kinds of characters the JavaScript interpreter might not like, that's why they should be encoded in the string literal... Commented Aug 26, 2011 at 16:52
  • Yeah, I was not thinking that through, my comment is incorrect in that regard. Commented Aug 26, 2011 at 17:52

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1. A JSON encoder is another possibility, if you've already got one in your project.
I'm using Spring... maybe it got one!?
I'm not aware of such a utility method in Spring. But using Spring doesn't prevent you from using commons-lang.
0

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.

1 Comment

Thanks for trying to help, I don't know who downvoted you up I upvoted to square things out. Even thought I accepted the other answer, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.