Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript single and double quotes for href's

I am having problem with escaping the single and double quotes inside the hrefs 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.

like image 354
naiveCoder Avatar asked Mar 06 '09 06:03

naiveCoder


People also ask

Should I use single quotes or double quotes in JavaScript?

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!

Can you use single quotes in JavaScript?

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.

How do you escape an apostrophe in JavaScript?

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 " .

How do you use double quotes in JavaScript?

to show double quote you can simple use escape character("\") to show it.


1 Answers

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

like image 185
Arthur Tarasov Avatar answered Oct 12 '22 00:10

Arthur Tarasov