简体   繁体   English

用JS中的特殊字符替换'和(字符

[英]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: 问题是,我找不到在JavaScript中的replace()函数中运行此字符串的方法,因为使用(或'或“会干扰其中一个特殊字符。该字符串来自JSP变量$ {displayName}。以下是引发“意外标识符”错误的一些尝试:

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. 以上方法均无效,请尝试使用字符串,包括(.encodeURI似乎也不起作用,这没有用,因为我希望HTML转义字符而不是URL。

The problem is that you're trying to access a JSP variable inside a JavaScript context. 问题是您正在尝试访问JavaScript上下文中的JSP变量。

You could print the variable's content inside a hidden div like so: 您可以像这样在隐藏的div打印变量的内容:

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

and then access it in JavaScript something like: 然后使用JavaScript进行访问,例如:

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. 我最终还是用JSP替换了字符串,因为没有大量的工作就无法将其包装在JS中。 Here is the answer: 答案是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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