JSTL function to replace quote chars inside a string?

前端 未结 2 1506
别那么骄傲
别那么骄傲 2020-12-20 14:50

What is the simplest way to replace quote characters with \\\" sequence inside string values?

相关标签:
2条回答
  • That'll be the fn:replace() function.

    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    ...
    ${fn:replace(foo, '"', '\\"')}
    

    Unrelated to the concrete question, this is an often recurring requirement in order to prevent malformed HTML when redisplaying user controlled input as a HTML attribute. Normally, you should use <c:out> or fn:escapeXml() for this instead. E.g.

    <input name="foo" value="<c:out value="${param.foo}" />" />
    <input name="foo" value="${fn:escapeXml(param.foo)}" />
    

    It not only takes quotes into account, but also all other XML special characters like <, >, &, etc.

    See also:

    • XSS prevention in JSP/Servlet web application
    0 讨论(0)
  • 2020-12-20 15:05

    Use javascript replace (with /g to replace all occurrences)

    string.replace(/"/g, '\\"')
    
    0 讨论(0)
提交回复
热议问题