简体   繁体   English

正则表达式替换'$ 1' - 为什么它是一个字符串?

[英]Regex substitution '$1' - why is it a string?

Silly question, but I'll ask it anyway: Why is the substitution part of a regular expression in JavaScript encompassed in quotes as a string, where it seems to be a variable in its own right? 愚蠢的问题,但无论如何我都会问:为什么JavaScript中正则表达式的替换部分包含在引号中作为字符串,它本身似乎是一个变量? eg '$2' 例如'$ 2'

alert("banana split") // nana split
function reg(afilename)
{
    var rexp = new RegExp(/^(ba)(.+)/gim)
    var newName = afilename.replace(rexp, '$2')
    return newName
}

Because it's not a [Javascript] variable in its own right. 因为它本身不是 [Javascript]变量。

If you didn't single-quote it, JavaScript would try to pass the value of the variable $2 as an argument (yes, you can give JavaScript variables names starting with $ ), except you don't have one. 如果你没有单引号,JavaScript会尝试将变量$2的值作为参数传递(是的,你可以给出以$开头的JavaScript变量名),除非你没有。

This way, the Regex engine gets the actual, literal string $2 , and gives it its own special meaning. 这样,Regex引擎获得实际的文字字符串$2 ,并赋予它自己的特殊含义。

It's a perfect example of abstraction, where you can witness two "layers" of software interacting. 这是一个完美的抽象示例,您可以在其中见证软件交互的两个“层”。 Consider also document.write('<p>Text</p>'); 还要考虑document.write('<p>Text</p>'); — you wouldn't want JavaScript to try to parse that HTML, right? - 你不希望JavaScript试图解析那个HTML,对吗? You want to pass it verbatim to the entity that is going to handle it. 您希望将其逐字传递给将要处理它的实体。

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

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