1252748
1252748

Reputation: 15362

a few questions on understanding a regex

This regular expression is supposed to capture an opacity value of an element if it has one, but I'm getting a little confused about what it's doing:

function getOpacity(elem) {
    var filter = elem.style.filter;
    return filter ? 
    filter.indexOf("opacity=") >= 0 ? (parseFloat(filter.match(/opacity=([^)]+)/)[1]) / 100) + "" : "" : elem.style.opacity;
}

It seems that there is a capture going on here ([^)]+). And that inside of it, one or more right parenthesis should be ignored [^)]+. I think I must have this wrong. What would one-or-more right parenthesis be ignored? That doesn't make sense.

In any case, then it seems that the regex ends, because after the last + mentioned, there is a /. Does this indicate the termination of the regEx? Immediately after that there is a call to the capture [1]. So maybe it is not actually over..?

Any help understand exactly what's going on here is appreciated. RegEx curtesy of the javascript ninja book

Upvotes: 0

Views: 82

Answers (5)

Blender
Blender

Reputation: 298106

[)] matches a closing parenthesis, while [^)] matches anything but a closing parenthesis. They're opposites. [^)]+ greedily matches any number of consecutive characters that aren't closing parentheses.

Upvotes: 1

go-oleg
go-oleg

Reputation: 19480

You almost got it right. [^)]+ means match one more non ")" characters.

Yes, / marks the end of the regex.

Upvotes: 1

Alex Gittemeier
Alex Gittemeier

Reputation: 5373

/ terminates the regex and the [1] part pulls the second index in the array. (In this case the second match)

Upvotes: 1

zerkms
zerkms

Reputation: 254886

[^)]+ - means 1 or more characters that are not closing parentheses.

So for filter: alpha(opacity=50) string the /opacity=([^)]+)/ would match 50

Upvotes: 2

AMADANON Inc.
AMADANON Inc.

Reputation: 5919

[^)]+ does not mean "ignore right brackets", it means "collect as many characters as possible (at least one) that is any character OTHER THAN right-bracket. In other words, everything up to the next close-right-bracket.

Upvotes: 4

Related Questions