By Alvin Alexander. Last updated: May 22, 2020
As a quick note to self, these are two Scala functions I just ran across that I’m putting here so I can find them in the future. The first function does what it says it does, inserting blank lines before HTML tags. It’s not perfect, but it’s a start for what I wanted when I couldn’t get “pretty printers” to do what I wanted:
def insertBlankLinesBeforeHtmlTags(originalHtml: String): String = {
val htmlAsSeq = convertStringWithNewlinesToSeq(originalHtml)
val spacedHtmlAsSeq: Seq[String] = for {
line <- htmlAsSeq
newLine = if (line.startsWith("<h")) {
s"\n\n${line}" //two blank lines before header tags
} else if (line.startsWith("<")) {
s"\n${line}" //one blank line before other html tags
} else {
line
}
} yield newLine
val htmlWithBlankLines = spacedHtmlAsSeq.mkString("\n")
htmlWithBlankLines
}
Next, this Scala function shows how to convert a String
into a Seq
by splitting the string on newline characters:
def convertStringWithNewlinesToSeq(s: String): Seq[String] =
s.split("\n").toVector
That’s all for today. As mentioned, I just came across these functions in some old code and wanted to put them here so I could find them again if/when needed.