Let's say I have an array with many Strings Called "birdBlue"
, "birdRed"
and some other animals like "pig1"
, "pig2"
).
Now I run a for loop that goes through the array and should return all birds. What comparison would make sense here?
Animals == "bird*"
was my first idea but doesn't work. Is there a way to use the operator * (or is there something similar to use?
Use this 'test' function which support for
*
and?
wildcardsYou could use Javascript's substring method. For example:
Which outputs:
Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.
So let's say your getting a pathname from a URL :
Let's say your at bird1?=letsfly - you could use this code to check the URL:
The above would match the first to URL's, but not the third (not the pig). You could easily swap out
url.substring(0,4)
with a regex, or even another javascript method like .contains()Using the
.contains()
method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:I think you meant something like "*" (star) as a wildcard for example:
or in your example: "bird*" => everything that starts with bird
I had a similar problem and wrote a function with RegExp:
If you want to read more about the used functions:
You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp
You should use RegExp (they are awesome) an easy solution is:
There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.
Fiddle