22

I have a string of HTML that I'm copy pasting into a String object that looks something like the following:

val s = """<body>
   <p>This is a test</p>  <p>This is a test 2</p>
 </body"""

The problem here is, when I display this string as JSON within the context of a web browser, the output displays literal \n and \t characters to the tune of something like this:

"<body>\n <p>This is a test</p>\t <p>This is a test 2</p>\n</body>"

Is it possible to perhaps strip all of these escaped sequences from my strings output in Scala?

randombits
  • 47,058
  • 76
  • 251
  • 433

1 Answers1

66

You could just

s.filter(_ >= ' ')

to throw away all control characters.

If you want to omit extra whitespace at the start/end of lines also, you can instead

s.split('\n').map(_.trim.filter(_ >= ' ')).mkString
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • That's really great. How come the filter didn't get rid of all white space and only the control characters? – randombits Jul 10 '13 at 22:36
  • 4
    @randombits - Because I filtered (in) everything above _or equal to_ space, and the control characters are all lower in value than space. – Rex Kerr Jul 10 '13 at 23:05