-2

I have an event that when triggered call a function like the following:

<a href="javascript:fav.delete(\''+addslashes(value.title)+'\')">

the function receive the string title as parameter and all works fine but when quotes are inside the string.

I used the function from other topic: Escaping String in Javascript

But the following error arises in console when click on the link:

Uncaught SyntaxError: Invalid or unexpected token

fav.delete('Y-Splitter 1/2\

I think the first occurence of the quote in string close href attribute.

How can I avoid this?

Community
  • 1
  • 1
Apalabrados
  • 1,098
  • 8
  • 21
  • 38

2 Answers2

1

You uses PHP with HTML and you question is about Javascript and HTML.

Solution in HTML + PHP:

<a href="javascript:fav.delete('<?php echo addslashes($valueTitle); ?>')">

$valueTitle don't exists, so you need set it to use.

Maybe you need use addslashes equivalent in javascript:

function addslashes(str) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0')
}

Use like:

<a href="javascript:fav.delete(addslashes(value.title))">...</a>

Full Example(try here):

function addslashes(str) {
  return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};

var fav = {
  'delete': function(str) {
    alert('Escape string :' + str);
  }
};

var value = {
  title: "You can't touch it!"
}
<a href="#" onclick="fav.delete(addslashes(value.title))">Click here</a>

You don't need apply single or double quotes when you use a function over another function like fv.delete(addslashes(...)).

Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73
  • I fetch content via Ajax and as I mentioned, I use the javascript addslashes function. – Apalabrados Dec 01 '16 at 19:18
  • @OlafErlandsen Weil, since the OP isn't tagged as php, how in the world is someone supposed to know that? addslashes() could certainly be a user-defined function in JavaScript. I hope you didn't down vote for that! – Scott Marcus Dec 01 '16 at 19:22
  • I update my answer with a example. `addslashes` don't exists on `javascript`, but you can create a equivalent. – Olaf Erlandsen Dec 01 '16 at 19:22
  • Your JavaScript example at the end (both here and on jsFiddle) alerts `Escape string :You can\'t touch it!` That backslash is out of place. – T.J. Crowder Dec 01 '16 at 19:28
  • @T.J.Crowder i know, but @apalabrados want use `addslashes` and it apply backslashes. – Olaf Erlandsen Dec 01 '16 at 19:30
  • @OlafErlandsen: The OP is clearly very confused, as `value.title` requires no escaping at all where the OP is trying to do escaping. – T.J. Crowder Dec 01 '16 at 19:31
-1

I'd go with this:

<a href="javascript:{var v= addslashes(value.title);fav.delete(v)}">

this way you pass a variable inside your call instead of rendering the string in place which causes a browser to stop at first double quotes inside that string.

Alexander Taran
  • 6,655
  • 2
  • 39
  • 60