Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing apostrophe to javascript function

I am not finding a solution on this one using JavaScript (to utilize localStorage) in a JSP.

Trying to pass something with apostrophe. I have done a .replaceAll() and replaced the ' with ' and it still passes it as an '.

I have also tried a .split("'") and replaced the apostrophe with:

(\' , ' , \', '' , ''' and  '\'')

All of these just pass an apostrophe to the function (what I see when I hover over the link) like this:

<a href="saveJob('<%=id%>','<%=title%>','<%=a%>' + '\'' + '<%=b%>','<%=date%>')">Save job</a>

With a and b being the two split substrings but with no effect. I do notice that spaces are converted into %20, but that's little comfort. Any other ideas?

like image 533
Dallas Avatar asked Oct 24 '25 04:10

Dallas


1 Answers

  1. Your JSP code is irrelevant. Decide what HTML you want to produce and produce it.
  2. The following are all valid HTML markup:

    <a href="saveJob('Bob\'s Question')"> …
    <a href="saveJob(&quot;Bob&apos;s Question&quot;)"> …
    <a href="saveJob('He said &quot;Go Away&quot;')"> …
    <a href='saveJob("He said \"Go Away\"")"> …
    

    … and the following are invalid:

    <a href="saveJob('Bob's Question')">       <!-- JS string ends early      -->
    <a href="saveJob("Bob's Question")">       <!-- HTML attribute ends early -->
    <a href="saveJob('Bob&apos;s Question')">  <!-- JS string ends early      -->
    <a href="saveJob('He said "Go Away"')">    <!-- HTML attribute ends early -->
    

    You cannot use your HTML attribute delimiter in your attribute value except as an HTML entity. You cannot use your JavaScript string delimiter in your JavaScript string unless you escape it, even if you use an HTML entity to describe it.

  3. In general, you should not be putting JavaScript in your HTML (you should attach event handlers to your markup programmatically, from script), and you especially shouldn't be abusing an HTML anchor as a JavaScript trigger (either use an HTML anchor to a valid URL and let JavaScript hijack the link if enabled, or use a <button> or other element to invoke script-only side effects).

like image 123
Phrogz Avatar answered Oct 25 '25 17:10

Phrogz