Is there a method yet that returns only a match and null if there is no match?
It may be a brain freeze but is there a method that just returns the match and null if not?
For example, if I want to just return the first variable or null otherwise:
var value:String = "image/png".toLowerCase();
var result:String = value.find(/image/(png|jpg|jpeg|gif)/);
if (result=="png") {
// do something
}
I know there's replace
and exec
and match
and they return arrays etc but I'm just looking for a method that returns my first match or null.
If there isn't this a function like this, I wish there was. How to god I wish there was.
There is no specific method that does that. The closest method is String.match
or RegExp.exec
and it makes little difference here since the regex has no global modifier. Once you use a regex with a global modifier, you will have no choice but to use RegExp.exec
.
Using String.match
or RegExp.exec
you can check if the result is null
and if it's not null
then extract the Group 1 value to check if it is png
:
var pattern:RegExp = /image\/(png|jpg|jpeg|gif)/;
var str:String = "image/png".toLowerCase();
var m:Array = pattern.exec(str);
if (m != null)
{
if (m[1] == "png") {
// Do stuff
}
}
Note that a /
must be escaped in a regex literal.
You can also contract the pattern a bit to (png|jpe?g|gif)
, but though it will work better internally, it will become less readable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.