user285594
user285594

Reputation:

Javascript - how to handle the single quote?

When i click the following it fails.

php render/html:

<div class="a" onclick="test('25', 'l'Espagne')" >

js:

function test(id, name) {
  alert(name); 
}

Upvotes: 1

Views: 259

Answers (4)

MatthewHinds
MatthewHinds

Reputation: 29

You'll need to escape it with a back slash "\". For example,

test('25', 'l\'Espagne')

For more information on escape characters, see

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Source: https://stackoverflow.com/a/21672439

Upvotes: 1

vol7ron
vol7ron

Reputation: 42089

You can use template literals if you're not worried about supporting old browsers (incl. IE):

function test(id, name) {
  alert(name);
}
<div class="a" onclick="test('25', `l'Espagne`)">Click Me</div>

Upvotes: 2

doublesharp
doublesharp

Reputation: 27599

Escape it with a backslash

test('25', 'l\'Espagne')

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

You can escape the quote mark with a \ whenever you need a single quote inside of a pair of single quotes. This also works for double quotes, if needed.

function test(id, name) {
  alert(name);
}
<div class="a" onclick="test('25', 'l\'Espagne')">Click Me</div>

Upvotes: 4

Related Questions