Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Replace newline, tab and return sequences from string

Tags:

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?

like image 443
randombits Avatar asked Jul 10 '13 22:07

randombits


People also ask

Does string trim remove newline?

Use String. trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

What is stripMargin in Scala?

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.

Does string trim remove newlines C#?

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.


1 Answers

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 
like image 53
Rex Kerr Avatar answered Sep 18 '22 13:09

Rex Kerr