简体   繁体   中英

Replace ' and ( characters with special characters in JS

I have a string I would like to display that is formatted like this:

("Cats"meow's, Jr.)

The problem is, I can't figure out a way to run this string in a replace() function in JavaScript because using either ( or ' or " will interfere with one of the special characters. The string comes from a JSP variable, ${displayName}. Here are some of the attempts that threw an 'Unexpected identifier' error:

var displayName = JSON.stringfy("${displayName}");
var displayName = "${displayName}".replace(/"/g, '"');
var displayName = '${displayName}'.replace(/"/g, '"'); 
var displayName = ${displayName}.replace(/"/g, '"'); 
var displayName = (${displayName}).replace(/"/g, '"');

None of the above works, try the string out, including the (. encodeURI doesn't seem to work either, and that's not useful since I want HTML escaped characters not URL.

The problem is that you're trying to access a JSP variable inside a JavaScript context.

You could print the variable's content inside a hidden div like so:

<div id="displayName" style="display: none"><%= displayName %></div>

and then access it in JavaScript something like:

var displayName = document.getElementById("displayName").innerHTML;

and use it to make the needed replaces.

I eventually went with replacing the string with JSP since wrapping it in JS was not working without significantly more work. Here is the answer:

<c:out value="${displayName}" escapeXml="true"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM