简体   繁体   English

JavaScript特殊转义字符

[英]Javascript special escaping characters

Hi I am using JavaScript function that is called from an anchor link which passes a title that has a special character could you please tell me how can I escape the single quote in the string passed to the function. 嗨,我正在使用从锚链接调用的JavaScript函数,该锚链接传递的标题具有特殊字符,您能否告诉我如何对传递给该函数的字符串中的单引号进行转义。

The sample string is given below, 示例字符串如下所示:

string desc="test's/test2'w";

sample link html 样本链接html

"<a href="javascript:getdata(\'' + desc+ '\',);void(0);">TEST</a>"

so the function getdata is not called since it's not escaping that character. 因此不会调用getdata函数,因为它没有转义该字符。

Its a legacy system I will need to work with HTML only 这是一个旧系统,我只需要使用HTML

Don't generate HTML by smashing together strings, use DOM. 不要通过将字符串粉碎在一起来生成HTML,而应使用DOM。 Don't use JavaScript URIs, use event handlers. 不要使用JavaScript URI,请使用事件处理程序。

var desc = "test's/test2'w";
var link = document.createElement('a');
link.appendChild( document.createTextNode('TEST') );
link.href = "fallback.html";
link.addEventListener('click', function (evt) {
    getData(desc);
    evt.preventDefault();
});
document.body.appendChild(link);

If you don't know the names of all the HTML entities, you can still HTML encode them 如果您不知道所有HTML实体的名称,仍可以对其进行HTML编码

function htmlEncode(str) {
    return str.replace(/[^\da-z()\[\] .,\/\\]/g, function (m) {
        return '&#' + m.charCodeAt(0) + ';';
    });
}
htmlEncode("test's/test2'w"); // "test&#39;s/test2&#39;w"

Where \\da-z()\\[\\] .,\\/\\\\ is the white list of permitted characters. 其中\\da-z()\\[\\] .,\\/\\\\是允许的字符的白名单。

If you want to generate HTML as Strings , this is okay, but if you want to make new DOM elements, Quentin 's answer is much better in the long run. 如果您想将HTML生成为Strings ,这是可以的,但是如果您要创建新的DOM元素,从长远来看, Quentin答案会更好。

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

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