I am having problem with escaping the single and double quotes inside the href
s JavaScript function.
I have this JavaScript code inside href
. It's like -
<a href = "javascript:myFunc("fileDir/fileName.doc", true)"> click this </a>
Now, since double quotes inside double quote is not valid, I need to escape the inner double quotes for it to be treated as part of the string - so, I need to do this -
<a href = "javascript:myFunc(\"fileDir/fileName.doc\" , true)"> click this </a>
The problem is, even the above code is not working. The JavaScript code is getting truncated at -- myFunc(
I tried with the single quote variation too - but even that doesn't seem to work (meaning that if I have a single quote inside my string literal then the code gets truncated).
This is what I did with a single quote:
<a href = 'javascript:myFunc("fileDir/fileName.doc" , true)'> click this </a>
This works, but if I have a single quote inside the string then the code gets truncated in the same way as that of double quotes one.
Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!
In JavaScript, single quotes ( '' ) and double quotes ( “” ) are used to create string literals. Most developers use single or double quotes as they prefer, and sometimes they let their code formatters decide what to use.
Using the Escape Character ( \ ) Using this method, we can use apostrophes in strings built with " . 'We\'re safely using an apostrophe in single quotes. ' We can also use quotation marks in strings built with " .
to show double quote you can simple use escape character("\") to show it.
In case anyone needs to escape some thing like this:
<a href="www.google.com/search?q="how+to+escape+quotes+in+href""</a>
You can use ASCII code for double quotes %22
:
<a href="www.google.com/search?q=%22how+to+escape+quotes+in+href%22"</a>
It is especially useful if you pass the link to JavaScript from PHP
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