Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline JS, how to escape a quote in a function parameter?

Is this a bug within JavaScript? http://jsfiddle.net/SommerEngineering/mr8sZ/

<a href='javascript:test("test")'>Works</a><br/>
<a href='javascript:test("test&quot;")'>Does not work</a>

Its looks like JS goes into the string, converts back the &quot; into " and then tries to execute the command, which is then of course wrong.

like image 401
SommerEngineering Avatar asked Jan 22 '26 09:01

SommerEngineering


2 Answers

You are correct. What you're writing there is html, so the html entity &quote; is rendered as a double quote ", then executed as JavaScript. Because test("test""); is not valid javascript, this will throw an error. If you want to pass test" into the function, you would escape the quote like this: test("test\"");

Inline JavaScript is not a good practice and has tons of non-intuitive issues. Read some of these results: Why is inline JS bad?

Here's an example of how to do this properly.

var a = document.getElementById('myElem');

a.addEventListener('click', function() {
  test('test"');
});

Just note there are many ways to get element references and you might want to use a class and attach the handler within a loop.

like image 65
m59 Avatar answered Jan 24 '26 00:01

m59


This is not a bug. The double quotes work because the HTML attribute has single quotes. However, the &quot; entity is evaluated by HTML, so the data passed to the JavaScript engine is:

javascript:test("test"")

If you want to escape the quotes use

javascript:test("test\"")

as a \ escapes the quote.

like image 39
PurkkaKoodari Avatar answered Jan 24 '26 00:01

PurkkaKoodari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!