- Don’t escape double quotes
- 2 Answers 2
- Javascript escape double quotes
- # Table of Contents
- # Escape Quotes in a String in JavaScript
- # Escaping double quotes in a String
- # Escaping quotes in a String with String.replaceAll()
- # Alternating quotes to avoid using backslashes
- # Using backticks instead of backslashes
- # Showing the escape characters in a string
- # Avoiding inline event handlers in HTML code
- How to escape and unescape quotes in JavaScript?
- 1 Answer 1
- How to properly escape double quotes in jquery
Don’t escape double quotes
This is just a wrong behaviour. I have a .js that I want to minify and this data have to go into a JSON. But the JSON API have to be like this.
Is there a way to configure uglifyJS that it don’t ignore \» At the moment I uglify my javascript and replace all my \» with placeholders. After this, I do a string replace with all placeholders to get it working. But then my tests don’t work. EDIT: The uglify version of my Javascript has to be valid JSON and valid Javascript as well. EDIT: As requested, a part of the real example. This code has to be uglified and then put into a JSON.
«This is just a wrong behaviour» — It isn’t. In JavaScript, in that context, the two statements mean exactly the same thing. Your problem is that you are depending on specific formatting of JS so that you can build JSON out of it by mashing strings together. Use a proper JSON library instead.
That is not the problem. I create dynamically a .js that I want to send to my backend. The API of my backend only takes JSON. So I send a valid JSON to it with the .js as a string. But in this .js string I need escaped double quotes otherwise, it dosesn’t work.
@DK1990 I don’t understand, can you give a simple, real example where
2 Answers 2
There’s a github issue about quote format.
The solution given in the link above is to tell uglify to keep the original quote format:
$ echo "console.log(\"foo\",'bar');" | uglifyjs --quotes=1 console.log('foo','bar'); $ echo "console.log(\"foo\",'bar');" | uglifyjs --quotes=2 console.log("foo","bar"); $ echo "console.log(\"foo\",'bar');" | uglifyjs --quotes=3 console.log("foo",'bar');
Or with gulp, give the following as parameter to the uglify.minify() function:
For your specific problem, as I’m not sure it will keep the unnecessary escape characters (in javascript), a solution would be:
- remove all single quotes from the javascript by switching everything to double quotes and escape them where necessary
- uglify the code with the above option
- do
If your javascript code has to have single quotes for some reason, instead you can replace the double quotes in the generated html in the javascript code by " or " .
Note that I don’t feel that something like var a = ‘abc \» def’; is valid javascript in the first place.
Another thing to look into would be how you include file (it’s not mentioned), maybe there’s a better way that directly loads the file into a string, on which you can then call JSON.stringify() .
If you use a recent javascript engine, you can also use backquotes (`) in your code and replace double or single quotes by them.
Or, if there’s no $ nor backquotes in your javascript code, you can simply do:
Javascript escape double quotes
Last updated: Dec 26, 2022
Reading time · 4 min
# Table of Contents
# Escape Quotes in a String in JavaScript
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. ‘that\’s it’ .
Copied!const escapeSingle = 'it\'s a string'; console.log(escapeSingle) // 👉️ it's a string const escapeDouble = "bobby\"hadz" console.log(escapeDouble) // 👉️ bobby"hadz
When we use the backslash character to escape a single or a double quote, we instruct JavaScript that we want to treat the quote as a literal single or double quote character and not as an end-of-string character.
If you use a single quote in a string that is wrapped in single quotes, you would terminate the string prematurely.
However, this is not the case when you use a backslash to escape the single quote.
# Escaping double quotes in a String
You can use the same approach to escape a double quote in a string.
Copied!const escapeDouble = "He said: \"test 123\"" console.log(escapeDouble) // 👉️ He said: "test 123"
We use a backslash \ character to escape each double quote in the string.
# Escaping quotes in a String with String.replaceAll()
You can also use the String.replaceAll() method to escape the quotes in a string.
Copied!// ✅ escape every single quote const str = "it's a string"; console.log(str); // 👉️ it's a string const result = str.replaceAll("'", "\\'"); console.log(result); // 👉️ it\'s a string
The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
pattern | The pattern to look for in the string. Can be a string or a regular expression. |
replacement | A string used to replace the substring match by the supplied pattern. |
The code sample escapes every single quote in a string.
Copied!// ✅ escape every single quote const str = "it's a string"; console.log(str); // 👉️ it's a string const result = str.replaceAll("'", "\\'"); console.log(result); // 👉️ it\'s a string
The same approach can be used to escape double quotes in a string.
Copied!// ✅ escape every double quote const str = 'it"s a string'; console.log(str); // 👉️ it"s a string const result = str.replaceAll('"', '\\"'); console.log(result); // 👉️ it\"s a string
The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn’t change the original string.
Strings are immutable in JavaScript.
# Alternating quotes to avoid using backslashes
Escaping a quote can be avoided by changing the outer quotes of the string.
Copied!const withSingle = "it's a string"; console.log(withSingle) // 👉️ it's a string const withDouble = 'He said: "test 123"' console.log(withDouble) // 👉️ He said: "test 123"
We alternate between double and single quotes, so we don’t have to escape them.
# Using backticks instead of backslashes
Note that you can also use backticks when defining a variable that stores a string. This allows you to use both single and double quotes in the string without having to escape them.
Copied!const withBoth = `it's a "test 123"`; console.log(withBoth) // 👉️ it's a "test 123"
The string is wrapped in backticks so we don’t have to escape the single and double quotes in its contents.
To add a backslash \ character to a string, add two backslashes next to one another.
The first backslash escapes the second, so the second is taken literally.
Copied!const addBackslash = "He said: \\\"test 123\\\"" console.log(addBackslash) // 👉️ He said: \"test 123\"
We have 3 backslashes next to one another. The first backslash escapes the second, so it is interpreted literally by JavaScript. The third backslash is used to escape the double quotes.
Here’s a more realistic example, where we only add a backslash to the string.
Copied!const addBackslash = "BMW \\1996\\" console.log(addBackslash) // 👉️ BMW \1996\
# Showing the escape characters in a string
If you need to show the escape characters in a string, use the JSON.stringify() method.
Copied!const addBackslash = 'BMW \\1996\\'; console.log(addBackslash); // 👉️ BMW \1996\ const withEscapeChars = JSON.stringify(addBackslash); console.log(withEscapeChars); // 👉️ "BMW \\1996\\"
The JSON.stringify method converts a JavaScript value to a JSON string.
When a value is converted to a JSON string, its output contains the escape characters.
# Avoiding inline event handlers in HTML code
If you got the error when using inline event handlers in HTML code, the best solution is to rewrite your code to use JavaScript and not use an inline event handler.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="box">bobbyhadz.comdiv> script type="module" src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const box = document.getElementById('box'); function handleClick() box.style.background = 'lime'; > box.addEventListener('click', handleClick); box.innerHTML = ` div id="box"> p title="example">bobbyhadz.comp> p>Hello worldp> div> `;
You can select the DOM element using the document.getElementById() method or the querySelector method.
Then you can add an event listener to the element or update its inner HTML markup.
Notice that we used backticks when setting the innerHTML property.
This enables us to use both single and double quotes when constructing the HTML markup.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to escape and unescape quotes in JavaScript?
If I change the first parameter of the new RegExp constructor in the unescapeQuotes method to 4 backslashes everything starts working as it should.
string.replace(new RegExp('\\\\"', 'g'),'"');
Why are four backslashes needed as the first parameter of the new RegExp constructor? Why doesn’t it work with only 2 of them?
Primitive constructors shouldn’t be used in most cases, including your case. Instead of new RegExp(‘\\»‘, ‘g’) , you should do /\\»/g to avoid unexpected weird string interpretations by the constructor (and incorrect returned values).
1 Answer 1
The problem is that you’re using the RegExp constructor, which accepts a string, rather than using a regular expression literal. So in this line in your unescape:
return string.replace(new RegExp('\\"', 'g'),'"');
. the \\ is interpreted by the JavaScript parser as part handling the string, resulting in a single backslash being handed to the regular expression parser. So the expression the regular expression parser sees is \» . The backslash is an escape character in regex, too, but \» doesn’t mean anything special and just ends up being » . To have an actual backslash in a regex, you have to have two of them; to do that in a string literal, you have to have four (so they survive both layers of interpretation).
Unless you have a very good reason to use the RegExp constructor (e.g., you have to use some varying input), always use the literal form:
var utility = < escapeQuotes: function(string) < return string.replace(/"/g, '\\"'); >, unescapeQuotes: function(string) < return string.replace(/\\"/g, '"'); >>;
How to properly escape double quotes in jquery
update: by deleting the space between the comma, I successfully got rid of one of the random equal signs/»s. However, it seems to be inserting » =»» » whenever there is a space in the string, which the user name returns(firstName lastName). Any idea why it would be doing that? And it also still inserts » =»» » right before «>join. «, which is strange considering there is no space there.
$("#ride").append('' + snapshot.val().user + '
- ' + snapshot.val().when + ' ' + snapshot.val().from + ' - ' + snapshot.val().to + '
- ' + snapshot.val().comments + '
');
data.forEach(function(snapshot) < $("#ride").append('' + snapshot.val().user + '
- ' + snapshot.val().when + ' ' + snapshot.val().from + ' - ' + snapshot.val().to + '
- ' + snapshot.val().comments + '
'); >); console.log('ID : ' + $("#ride").html()); >);
These are the divs created by my jquery code. Currently, I get a «Uncaught SyntaxError: Unexpected token >» message when I click either of the buttons in this div:
Liz
- Wed Mar 29 2017 07:00 AM - 09:00 PM
- test 2
Liz
- Thu Mar 23 2017 02:00 AM - 05:30 AM
- TEST THREE
Why does my initMessenger call all these random equal signs everywhere and added quotation marks? How do I get rid of them?