0

I have an onClick call on a link:

<a onClick="fomateName('Andrew Dsouza')"> //this is working good

The problem is the variable inside fomateName would contain single quotes and my fomateName Takes a variable like

var a='Andrew D'souza'. Need to format a variable present with single quote Ex;

<a onClick="fomateName('a')"> which turns to 

<a onClick="fomateName('Andrew D'souza')"> //this is not working ,because present of single quote

Any Idea how to pass text with proper quotes in a javascript.

with single quote not the name actually

6 Answers 6

2

Try:

<a onClick="fomateName('Andrew D\'souza')"> <!-- this will work -->

\ use backslashes to escape '

Lets say if you have function like this =>

function fomateName(txt){
    alert(txt);
}

and invoking it from anchor =>

<a onClick="fomateName('Andrew D\'souza')"> <!-- this will alert "Andrew D'souza" -->
Sign up to request clarification or add additional context in comments.

7 Comments

I need to format the variable which reolves to a name Like Andre D'souza
If you pass a variable through you wont need to worry about escaping it should just work.
@saum22 When you have wrapped params inside function in single quotes '' and want variable including same ' (single quote) you have to use \ before '
but how to do it for a variable which contains single quote
@saum22 you can define variable like this => var a = "Andrew D'souza"; or var a = 'Andrew D\'souza'; , but I suggest to use double quotes
|
1

Escape the quote with backslashes.

<a onClick="fomateName('Andrew D\'souza')">
//this is not working ,because present of single quote

Comments

0

You can wrap it in double quotes like so:

   <a onClick="fomateName("Andrew D'souza")"> //this is not working ,because present of single quote

Never mind, just realized it already has double quotes, yeah use backslash for escape like so:

  <a onClick="fomateName('Andrew D\'souza')">

Comments

0

Try this. Use backslash - It will escape the quote breaks

<a onClick="fomateName('Andrew D\'souza')"> 

Comments

0

You can use escape character

<a onclick="formateName('AdrewD\'souza')">

Comments

0

You can escape the quote with a backslash..

fomateName('Andrew D\'souza');

This should work anyway:

var name = "Andrew D'souza";
fomateName(name);

2 Comments

but its not working for a a variable call present with single quote
@saum22 <a onClick="fomateName('a')"> should be <a onClick="fomateName(a)">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.