How to use both single and double quotes inside JS

2019-01-28 05:14发布

问题:

I want to call fn:replace inside EL inside c:out to replace quote caracters.

The following does not work

<c:out value="${fn:replace(userName,'"','\\"')}"/>

because XML parser stops at first double quote and sees no c:cout tag termination (JSP compilation stage error).

The following

<c:out value="${fn:replace(userName,'&quot;','\\&quot;')}"/>

does not work, probably because replace function does not see actual quote character.

回答1:

Parameterize them with <c:set>.

<c:set var="search" value='"' />
<c:set var="replace" value='\\"' />
<c:out value="${fn:replace(userName, search, replace)}"/>

Unrelated to the concrete question, have you still not considered a real JSON generator? With for example Gson it's a matter of the following oneliner, given that user is a fullworthy Javabean:

String json = new Gson().toJson(user);

You'll get syntactically valid JSON directly without fiddling all ways to get JSP/JSTL/EL to produce valid JSON.