Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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". How can I solve this problem?

like image 505
Yujun Wu Avatar asked Nov 25 '12 20:11

Yujun Wu


1 Answers

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.

like image 106
Hektor Avatar answered Oct 08 '22 07:10

Hektor