OWASP library custom policy - adding spaces where removing html

Viewed 55

I am currently trying to use the OWASP library to remove some html from a string. A string that I have is a list:

  1. one
  2. two
  3. three

Which in markup, the string looks like "<ul><li>one</li><li>two</li><li>three</li></ul>".

When I use the OWSAP library with a policy like:

PolicyFactory policy = new HtmlPolicyBuilder()
                .allowUrlProtocols("https")
                .allowStandardUrlProtocols()
                .requireRelNofollowOnLinks()
                .toFactory();

OSWAP converts the list to: "onetwothree" . I instead would like to add spaces between the list items, and be able to convert the string to "one two three". I was wondering how / if there is a way to do this with OWSAP? I am new to using this so any advice is appreciated!

1 Answers

This is how it works, in case someone in future faced the same issue It's in kotlin but pretty simple to be converted to java

private class SeparateTextPostProcessor(htmlStreamEventReceiver: HtmlStreamEventReceiver, val separator: String = " ") :
    HtmlStreamEventReceiverWrapper(htmlStreamEventReceiver) {
    override fun text(elem: String) {
        if (elem.isNotEmpty()) {
            // adds a space between elements
            underlying.text("$elem$separator")
        } else {
            underlying.text(elem)
        }
    }
}

fun String.stripHTML(): String {
    val policy =
      HtmlPolicyBuilder().withPostprocessor { SeparateTextPostProcessor(it) }.toFactory()
    val sanitized = policy.sanitize(this)
    // Sanitized text will contain additional escaped characters.
    return sanitized.trim()
}
Related