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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With