JavaScript 中的转义引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2004168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:21:01  来源:igfitidea点击:

Escape quotes in JavaScript

javascriptquotesescaping

提问by Matt Dawdy

I'm outputting values from a database (it isn't really open to public entry, but it is open to entry by a user at the company -- meaning, I'm not worried about XSS).

我正在从数据库输出值(它并不是真正对公众开放,但它对公司的用户开放——也就是说,我不担心XSS)。

I'm trying to output a tag like this:

我正在尝试输出这样的标签:

<a href="" onclick="DoEdit('DESCRIPTION');">Click Me</a>

DESCRIPTION is actually a value from the database that is something like this:

描述实际上是来自数据库的一个值,如下所示:

Prelim Assess "Mini" Report

I've tried replacing " with \", but no matter what I try, Firefox keeps chopping off my JavaScript call after the space after the word Assess, and it is causing all sorts of issues.

我试过用 \ 替换 ",但无论我尝试什么,Firefox 都会在单词Assess后面的空格后切断我的 JavaScript 调用,这导致了各种各样的问题。

I must bemissing the obvious answer, but for the life of me I can't figure it out.

我必须忽略明显的答案,但对于我的生活,我无法弄清楚。

Anyone care to point out my idiocy?

有人愿意指出我的愚蠢吗?

Here is the entire HTML page (it will be an ASP.NETpage eventually, but in order to solve this I took out everything else but the problem code)

这是整个 HTML 页面(它最终将是一个ASP.NET页面,但为了解决这个问题,我取出了除问题代码之外的所有其他内容)

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment \"Mini\"'); return false;">edit</a>
    </body>
</html>

回答by Aaron

You need to escape the string you are writing out into DoEditto scrub out the double-quote characters. They are causing the onclickHTML attribute to close prematurely.

您需要转义要写入的字符串DoEdit以清除双引号字符。它们导致onclickHTML 属性过早关闭。

Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, &quot;.

\在 HTML 上下文中使用 JavaScript 转义字符是不够的。您需要将双引号替换为正确的 XML 实体表示形式&quot;.

回答by tsemer

&quot;would work in this particular case, as suggested before me, because of the HTML context.

&quot;由于 HTML 上下文,正如我之前建议的那样,在这种特殊情况下会起作用。

However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
'becomes \x27
"becomes \x22

但是,如果你希望你的JavaScript代码能够独立逃过任何情况下,你可以选择本地JavaScript编码:
'\x27
"\x22

So your onclick would become:
DoEdit('Preliminary Assessment \x22Mini\x22');

所以你的 onclick 会变​​成:
DoEdit('Preliminary Assessment \x22Mini\x22');

This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert()is an easy test method for this).

例如,当将 JavaScript 字符串作为参数传递给另一个 JavaScript 方法(这alert()是一个简单的测试方法)时,这也适用。

I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.

我指的是重复的 Stack Overflow 问题,如何在 onClick 处理程序中转义 JavaScript 代码中的字符串?.

回答by kristian

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
    </body>
</html>

Should do the trick.

应该做的伎俩。

回答by rohtakdev

Folks, there is already the unescapefunction in JavaScript which does the unescaping for \":

伙计们,unescapeJavaScript 中已经有一个函数可以对 进行转义\"

<script type="text/javascript">
    var str="this is \"good\"";
    document.write(unescape(str))
</script>

回答by dl.

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

问题是 HTML 无法识别转义字符。您可以通过使用 HTML 属性的单引号和 onclick 的双引号来解决这个问题。

<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>

回答by Ronnie Royston

This is how I do it, basically str.replace(/[\""]/g, '\\"').

这就是我的做法,基本上str.replace(/[\""]/g, '\\"')

var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\"');

//will return class=\"whatever-foo__input\" id=\"node-key\"
<span id="output"></span>

回答by iTake

If you're assembling the HTML in Java, you can use this nice utility class from Apache commons-lang to do all the escaping correctly:

如果您在 Java 中组装 HTML,您可以使用 Apache commons-lang 中的这个不错的实用程序类来正确执行所有转义:

org.apache.commons.lang.StringEscapeUtils
Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.

org.apache.commons.lang.StringEscapeUtils
转义和取消转义 Java、Java Script、HTML、XML 和 SQL 的字符串。

回答by rahul

I have done a sample one using jQuery

我使用 jQuery 做了一个示例

var descr = 'test"inside"outside';
$(function(){
   $("#div1").append('<a href="#" onclick="DoEdit(descr);">Click Me</a>');       
});

function DoEdit(desc)
{
    alert ( desc );
}

And this works in Internet Explorer and Firefox.

这适用于 Internet Explorer 和 Firefox。

回答by Dinesh Lomte

Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.

请在下面的代码中找到使用正则表达式将单引号作为输入字符串的一部分进行转义的代码。它验证用户输入的字符串是否以逗号分隔,同时它甚至会转义作为字符串一部分输入的任何单引号。

In order to escape single quotes, just enter a backward slash followed by a single quote like: \'as part of the string. I used jQuery validator for this example, and you can use as per your convenience.

为了转义单引号,只需输入一个反斜杠,后跟一个单引号,例如:\'作为字符串的一部分。我在这个例子中使用了 jQuery 验证器,你可以根据自己的方便使用。

Valid String Examples:

有效字符串示例:

'Hello'

'你好'

'Hello', 'World'

'你好,世界'

'Hello','World'

'你好,世界'

'Hello','World',' '

'你好,世界',' '

'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'

'这是我的世界','没有我就不能享受这个。','欢迎,客人'

HTML:

HTML:

<tr>
    <td>
        <label class="control-label">
            String Field:
        </label>
        <div class="inner-addon right-addon">
            <input type="text" id="stringField"
                   name="stringField"
                   class="form-control"
                   autocomplete="off"
                   data-rule-required="true"
                   data-msg-required="Cannot be blank."
                   data-rule-commaSeparatedText="true"
                   data-msg-commaSeparatedText="Invalid comma separated value(s).">
        </div>
    </td>

JavaScript:

JavaScript:

     /**
 *
 * @param {type} param1
 * @param {type} param2
 * @param {type} param3
 */
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {

    if (value.length === 0) {
        return true;
    }
    var expression = new RegExp("^((')([^\'\\]*(?:\\.[^\'\\])*)[\w\s,\.\-_\[\]\)\(]+([^\'\\]*(?:\\.[^\'\\])*)('))(((,)|(,\s))(')([^\'\\]*(?:\\.[^\'\\])*)[\w\s,\.\-_\[\]\)\(]+([^\'\\]*(?:\\.[^\'\\])*)('))*$");
    return expression.test(value);
}, 'Invalid comma separated string values.');

回答by omanosoft

You can copy those two functions (listed below), and use them to escape/unescape all quotes and special characters. You don't have to use jQuery or any other library for this.

您可以复制这两个函数(如下所列),并使用它们来转义/取消转义所有引号和特殊字符。您不必为此使用 jQuery 或任何其他库。

function escape(s) {
    return ('' + s)
        .replace(/\/g, '\\')
        .replace(/\t/g, '\t')
        .replace(/\n/g, '\n')
        .replace(/\u00A0/g, '\u00A0')
        .replace(/&/g, '\x26')
        .replace(/'/g, '\x27')
        .replace(/"/g, '\x22')
        .replace(/</g, '\x3C')
        .replace(/>/g, '\x3E');
}

function unescape(s) {
    s = ('' + s)
       .replace(/\x3E/g, '>')
       .replace(/\x3C/g, '<')
       .replace(/\x22/g, '"')
       .replace(/\x27/g, "'")
       .replace(/\x26/g, '&')
       .replace(/\u00A0/g, '\u00A0')
       .replace(/\n/g, '\n')
       .replace(/\t/g, '\t');

    return s.replace(/\\/g, '\');
}