Ghoul Fool
Ghoul Fool

Reputation: 6949

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? eg '$2'

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

Upvotes: 1

Views: 72

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

Because it's not a [Javascript] variable in its own right.

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.

This way, the Regex engine gets the actual, literal string $2, and gives it its own special meaning.

It's a perfect example of abstraction, where you can witness two "layers" of software interacting. Consider also document.write('<p>Text</p>'); — you wouldn't want JavaScript to try to parse that HTML, right? You want to pass it verbatim to the entity that is going to handle it.

Upvotes: 3

Related Questions