myRegExp.test( sourceString ) in ECMAScript 262
Run the regular expression against a string; return true
if a match exists, false
otherwise.
Arguments
name | type | description |
---|---|---|
sourceString | String | The string to run the regular< |
- Return Type
- Boolean
Description
This method is equivalent to myRegExp.exec(sourceString)!=null
(but slightly faster in the success case, since no array needs to be created). This method is appropriate when a simple test for the presence of a match is all that is needed.
function UserSaidOK(userInput){
var validResponses = /\b(ok|yes|1|true|go|yup)\b/i;
return validResponses.test(userInput);
}
if (UserSaidOK("I do not authorize this action!")){
// this code will not execute...
// validResponses.test(...) in the above function returns false for this string
}
Note that, like RegExp.exec()
, if the global flag for this regular expression is set, repeated calls to this function will update the lastIndex
property of the expression, which will eventually cause repeated calls to test()
to return false, after the string has been exhausted.
var msg = "Hello World";
var hasAVowel = /[aeiou]/i;
var hasAVowel2 = /[aeiou]/ig;
hasAVowel.test(msg); //true -- matched the 'e'
hasAVowel2.test(msg); //true -- matched the 'e'
hasAVowel.test(msg); //true -- matched the 'e'
hasAVowel2.test(msg); //true -- matched the first 'o'
hasAVowel.test(msg); //true -- matched the 'e'
hasAVowel2.test(msg); //true -- matched the second 'o'
hasAVowel.test(msg); //true -- matched the 'e'
hasAVowel2.test(msg); //false -- no further vowels were found
hasAVowel.test(msg); //true -- matched the 'e'
hasAVowel2.test(msg); //true -- started over and matched the 'e'