Question

Just a string. Add \' to it every time there is a single quote.

Was it helpful?

Solution

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'");

OTHER TIPS

Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().

function addslashes(string) {
    return string.replace(/\\/g, '\\\\').
        replace(/\u0008/g, '\\b').
        replace(/\t/g, '\\t').
        replace(/\n/g, '\\n').
        replace(/\f/g, '\\f').
        replace(/\r/g, '\\r').
        replace(/'/g, '\\\'').
        replace(/"/g, '\\"');
}

A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);

Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

To be sure, you need to not only replace the single quotes, but as well the already escaped ones:

"first ' and \' second".replace(/'|\\'/g, "\\'")

An answer you didn't ask for that may be helpful, if you're doing the replacement in preparation for sending the string into alert() -- or anything else where a single quote character might trip you up.

str.replace("'",'\x27')

That will replace all single quotes with the hex code for single quote.

var myNewString = myOldString.replace(/'/g, "\\'");
var str = "This is a single quote: ' and so is this: '";
console.log(str);

var replaced = str.replace(/'/g, "\\'");
console.log(replaced);

Gives you:

This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
             .replace(/'/g, ''') /* The 4 other predefined entities, required. */
             .replace(/"/g, '"')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top