简体   繁体   中英

Can't replace \ or escape character in string in Node JS

I have a string with backslash or escape character and curly braces. I am trying to replace these backslash or escape character and curly braces with an empty string using this code:

const regex = /[{}\\]/g
const s = "<speak>time=\"500ms\"/></speak>{1}";
console.log(s.replaceAll(regex, ''));

I am expecting this as the output:

time="500ms"/>1

The code works on all web editors I have tried, but not during runtime in actual code. The code replaces the curly braces during runtime but not the backslash or escape character. Is there anything that stands out as wrong?

The code works on all web editors I have tried

Because replaceAll As of August 2020 Modern browsers have support it!

but not during runtime

I think in runtime env you run an old version of node! So install version NodeJS 15+ which support replaceAll method!

Or you could just use only replace with flag g which do same as replaceAll

 const regex = /(<.*?>|[\{\}])/g const s = "<speak>time=\"500ms\"/></speak>{1}"; console.log(s.replace(regex, ''));//time="500ms"/>1

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