简体   繁体   中英

How to replace all \ char into ' in javascript

if, a = "Bob\\'s house"

how would you replace the backslash with another ' ? I want a to equal "Bob''s house"

I would assume that I can do a.replace("\\", "'") but this doesn't work

It does not work because \\' is treated as a single character. In Javascript \\ is used to initiate an escape character, which means "literally the character after \\".

In order to show \\ you therefore need to write \\\\ . And if you want to change escaped ' into '' what you need to do is simply a.replace("\\'", "\\'\\'") ;

basically a = "Bob\\'s house" is interpreted as "Bob's house" , youre just escaping the ' . there is no backslash in the string.

to have your wanted result ( "Bob''s house" ), simply do the following:

a.replace("\'", "\'\'")

正如user2182349所说, a.repalce("\\\\", "'")

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