简体   繁体   English

在JavaScript中逃避单引号

[英]Escape single quote in JavaScript

I wrote a function as: 我写了一个函数:

function makeTitleEditable($titleContainer){
        var defaultValue = $titleContainer.text().replace("'","\\'");
        $titleContainer.replaceWith("<input id='poll_title' name='poll[title]' value='" + defaultValue +"' type='text'>");
      }

Now the problem was I still can't escape the single quote. 现在问题是我仍然无法逃脱单引号。 For example, if 例如,如果

$titleContainer.text() => I'm lucky

console.log("<input id='poll_title' name='poll[title]' value='" + defaultValue +"' type='text'>") => <input id='poll_title' name='poll[title]' value='I\'m lucky!' type='text'> 

which would generate DOM with value "I" rather than "I'm lucky". 这将生成值为“I”而不是“我很幸运”的DOM。 How can I solve this problem? 我怎么解决这个问题?

Of course the quick fix is simply to replace "'" with "\\'" although that really isn't scalable on copy-and-paste-type basis. 当然,快速修复只是用"\\'"替换"'" ,尽管在复制和粘贴类型的基础上它实际上是不可扩展的。
Better would be via a regex, such as: 更好的是通过正则表达式,例如:

var badString = "Visit John's Site!!!";
var goodString = badString.replace(/'/g, "\'");

Remember though that they'll then show up server-side or even in subsequent function calls as simple apostrophes again, so if you're planning to pass them around between different functions, another solution might be preferable: 但请记住,它们会再次显示服务器端或甚至后续函数调用中的简单撇号,因此如果您计划在不同函数之间传递它们,则另一种解决方案可能更可取:

var badString = "Visit John's Site!!!";
var goodString = badString.replace(/'/g, "\x27");

This is the standard Unicode character for an apostrophe. 这是撇号的标准Unicode字符。 This won't necessarily avoid any subsequent function calls giving a problem, but it means the string won't have to be decoded. 这不一定会避免任何后续函数调用产生问题,但这意味着不必解码字符串。

Use jQuery to set the value; 使用jQuery设置值;

function makeTitleEditable($titleContainer){
    $titleContainer.replaceWith(
       $("<input id='poll_title' name='poll[title]' type='text'>").val($titleContainer.text())
    );
}

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

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