简体   繁体   中英

Escape string in javascript

I need to escape this string somehow (with newlines):

:-\\
"123"
:-/

And get this after escaping:

:-\\\\n\\"123\\"\\n:-/

I tried this, but it's not what I needed.

:-\\\n/"123/"\n:-/      .replace(/"/g,'/\"')
:-\\\n/"123/"\n:-/      .replace(/"/g,'\/"')
:-\\\n\\"123\\"\n:-/    .replace(/"/g, '\\"') ???

Don't mess with replaces, use JSON.stringify :

 text = document.querySelector('pre').textContent; text = JSON.stringify(text).slice(1, -1) alert(text) 
 <pre> :-\\ "123" :-/ </pre> 

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