[javascript] How do I add slashes to a string in Javascript?

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

The answer is


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.


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.


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


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

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

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, '\\"');
}

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: \'

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to string-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format in kotlin string templates Converting Float to Dollars and Cents Chart.js - Formatting Y axis String.Format not work in TypeScript Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to left align a fixed width string? Convert Java Date to UTC String Format a Go string without printing?

Examples related to backslash

How to print a single backslash? python replace single backslash with double backslash Escaping backslash in string - javascript File path issues in R using Windows ("Hex digits in character string" error) Replace "\\" with "\" in a string in C# How to remove backslash on json_encode() function? Java replace issues with ' (apostrophe/single quote) and \ (backslash) together How do I add slashes to a string in Javascript? String.replaceAll single backslashes with double backslashes Escaping Strings in JavaScript