Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get an apostrophe in a string in javascript

Tags:

javascript

I'm doing some stuff with javascript and I'm wondering, how do I put an apostrophe in a string in javascript?

theAnchorText = 'I apostrophe M home'; 
like image 845
webmasters Avatar asked Jun 06 '11 20:06

webmasters


People also ask

How do you write an apostrophe with strings?

In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string. There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

How do you escape an apostrophe in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

How do I change the apostrophe in JavaScript?

replace(/'/g, 'A');


Video Answer


2 Answers

You can use double quotes instead of single quotes:

theAnchorText = "I'm home"; 

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home'; 

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

like image 185
icktoofay Avatar answered Sep 29 '22 15:09

icktoofay


You can try the following:

theAnchorText = "I'm home"; 

OR

theAnchorText = 'I\'m home'; 
like image 33
legendofawesomeness Avatar answered Sep 29 '22 14:09

legendofawesomeness