admin管理员组文章数量:1289584
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". How can I solve this problem?
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". How can I solve this problem?
Share Improve this question edited May 4, 2015 at 16:10 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Nov 25, 2012 at 20:16 Yujun WuYujun Wu 3,01212 gold badges41 silver badges56 bronze badges 1- Why don´t you using double quotes for your attributes? – TimWolla Commented Nov 25, 2012 at 20:50
2 Answers
Reset to default 5Of 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. 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;
function makeTitleEditable($titleContainer){
$titleContainer.replaceWith(
$("<input id='poll_title' name='poll[title]' type='text'>").val($titleContainer.text())
);
}
本文标签: jqueryEscape single quote in JavaScriptStack Overflow
版权声明:本文标题:jquery - Escape single quote in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741439599a2378836.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论