3

I'm trying to detect if the CSS attribute filter of an element already contains some rules. But my regex never finds any match : /saturate\(.[^\)]\)/

Here's a demo for you guys :

var filter = $('div').css('filter');

$('p').eq(0).text(filter.search(/saturate\(.[^\)]\)/)); //Should return something else than -1
$('p').eq(1).text(filter.search(/contrast\(.[^\)]\)/)); //Should return -1
div{
  filter: brightness(1.9) saturate(80%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

<p></p>
<p></p>

1
  • Use \([^)]+\) instead of \(.[^\)]\) Commented Aug 3, 2017 at 14:39

2 Answers 2

4

You're missing a + in your regex

var filter = $('div').css('filter');
//                                               V here!
$('p').eq(0).text(filter.search(/saturate\(.[^\)]+\)/)); //Should return something else than -1
$('p').eq(1).text(filter.search(/contrast\(.[^\)]+\)/)); //Should return -1
div{
  filter: brightness(1.9) saturate(80%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

<p></p>
<p></p>

Sign up to request clarification or add additional context in comments.

Comments

1

You should use \([^)]+\) instead of \(.[^\)]\) in your regexps:

var filter = $('div').css('filter');

$('p').eq(0).text(filter.search(/saturate\([^)]+\)/)); // 16
$('p').eq(1).text(filter.search(/contrast\([^)]+\)/)); // -1
div{
  filter: brightness(1.9) saturate(80%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

<p></p>
<p></p>

The \(.[^\)]\) matches (, then any char other than a line break char (with .), and then a single char other than ) (your negated character class [^\)]), and then a literal ).

The \([^)]+\) will match

  • \( - a literal (
  • [^)]+ - 1 or more chars other than )
  • \) - a literal ).

3 Comments

Oh, you don't have to escape the ) inside the [] ?
@Zenoo: No, no need escaping ( and ). Only ^, \, ] and - require escaping (though in some cases, ^, and - may be used as literals inside character classes, too).
Thanks, I didn't know that !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.