简体   繁体   English

逃避字符串中的正则表达式

[英]Escape regex within string

I have a large piece of HTML/CSS/JS which gets served to 3rd party sites via a script tag. 我有一大块HTML / CSS / JS,它通过脚本标签提供给第三方网站。 The script tag has an id which I use to match and insert the content at the correct location (no nasty document.write ). 脚本标记有一个id,我用它来匹配并在正确的位置插入内容(没有讨厌的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. 正确转义前面和后面的行,中间行的语法对我来说是正确的,但它会抛出“意外的输入结束”错误,WebKit Inspector将其显示为未转义。 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. 正则表达式的目的是从$ amount和百分比中删除特殊字符(示例值可能是“$ 1,000”或“5.5%”。我尝试不使用RegExp对象而只是执行`/ [\\ $%,] / ig和我得到完全相同的问题。

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. 编辑:根据Felix的评论将其更改为\\\\\\\\ 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: 然后,该字符串位于另一个字符串中,用于评估:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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