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?
Use String. trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
Often in text processing a string has a "start" character that ends its leading margin. Whitespace chars (like spaces) may precede this. Here With stripMargin we handle this case. We eliminate the entire margin (leading blanks and separator) from the strings in a list.
To trim a string like that we use C#'s Trim() method. One version of this method accepts characters to cut from both sides of the string. When we specify the carriage return character ( \r ) and line feed character ( \n ) there, the method removes all leading and trailing newlines.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With