简体   繁体   中英

Escape regex within string

I have a large piece of HTML/CSS/JS which gets served to 3rd party sites via a script tag. The script tag has an id which I use to match and insert the content at the correct location (no nasty document.write ). However, I've come across a really odd error. Any line with a regex in it seem to escape itself from the string. Below is an example of a problem line (one of a few that are causing problems):

+"        // preceding code"
+"        var remSpc = new RegExp('[\$%,]', 'ig');"
+"        // following code"

The preceding and following lines are correctly escaped, the syntax for the middle line looks correct to me, but it's throwing an "unexpected end of input" error and WebKit Inspector is showing it as being unescaped. Screen below to show what I mean by unescaped:

在此输入图像描述

The purpose of the regex is to remove special characters from $ amounts and percentages (example values might be "$1,000" or "5.5%". I've tried not using a RegExp object and instead just doing `/[\\$%,]/ig and I get exactly the same problem.

NB the issue is not with this regex in particular, I have a few regexs and every line containing one is behaving the same way.

A string within a string should be doubly escaped:

//...
+"        var remSpc = new RegExp('[\\\\$%,]', 'ig');"

The first \\ is to escape the second \\ .

Edit: Changed it to \\\\\\\\ as per Felix's comment. We need this because normally it would be:

/...\$.../

But, the regex is in a string so:

'...\\$...'

And, then, that string is in another string, intended to be evaluated:

"...'...\\\\$....'..."

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