Languages
[Edit]
EN

Java - escape html special characters using spring HtmlUtils.htmlEscape with unit test for most common cases

3 points
Created by:
Marley-Marks
442

Quick solution:

public class HtmlUtils {

    public static String escape(String html) {
        return org.springframework.web.util.HtmlUtils.htmlEscape(html, "UTF-8");
    }
}

Unit tests:

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class HtmlUtilsTest {

    @Test
    void shouldEscapeSpecialHtmlCharacters() {
        assertThat(HtmlUtils.escape("\"")).isEqualTo(""");
        assertThat(HtmlUtils.escape("<")).isEqualTo("&lt;");
        assertThat(HtmlUtils.escape(">")).isEqualTo("&gt;");
        assertThat(HtmlUtils.escape("&")).isEqualTo("&amp;");
        assertThat(HtmlUtils.escape("'")).isEqualTo("&#39;");
    }
}

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join