简体   繁体   中英

Escaping a single quote in Javascript

We're getting the firstName and lastName of customers which may contain a single quote in it. If one of the names contains a single quote, I get a script error 'Expected ";"'.

The snippet to greet the customer is:

greeting = "Guten Tag " + '<xsl:value-of select="cognetic_core_person/@person_firstName" />' + "&nbsp;" +'<xsl:value-of select="cognetic_core_person/@person_lastName" />' + "!";

I can't just use the double quote as there are double quotes in it. So

replace( /'/g , "\'") 

or something similar is not working and the only proposals I've found so far.

make it

replace( /'/g , "\\\'") 

for example

"as's".replace( /'/g , "\\\\\\'") //outputs as\\'s

basically you need to use single slash 3 times, one slash is to escape slash itself and one to escape the quote.

Repace ' with ` (near escape key)

O'Doil will be O`Doil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM