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
Add a ment  | 

2 Answers 2

Reset to default 5

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. 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