JSTL function to replace quote chars inside a string?
Asked Answered
Z

2

11

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

Zenaidazenana answered 17/1, 2012 at 16:23 Comment(0)
H
16

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:

Hyacinthie answered 17/1, 2012 at 16:28 Comment(2)
I am creating JSON with JSP, so the direct requirement is to escape quotes. Some data is used to display on page later so it may also require HTML escaping too. Thanks for a link!Zenaidazenana
I'd rather use a fullworthy JSON tool and for sure not do the job in a JSP. Start here for some concrete examples: #4113186 Or if your environment allows it, go for a JAX-RS webservice: https://mcmap.net/q/225987/-servlet-vs-restfulHyacinthie
W
-7

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

string.replace(/"/g, '\\"')
Wyrick answered 17/1, 2012 at 16:28 Comment(1)
I am on server-sine, in JSP file, can't pass to JSZenaidazenana

© 2022 - 2024 — McMap. All rights reserved.