awesome-string
Version:
The ultimate JavaScript string library
37 lines (36 loc) • 1.21 kB
JavaScript
import coerceToString from 'helper/string/coerce_to_string';
import toString from 'helper/string/to_string';
/**
* Checks whether `subject` matches the regular expression `pattern`.
*
* @function matches
* @static
* @since 1.0.0
* @memberOf Query
* @param {string} [subject=''] The string to verify.
* @param {RegExp|string} pattern The pattern to match. If `pattern` is not RegExp, it is transformed to `new RegExp(pattern, flags)`.
* @param {string} [flags=''] The regular expression flags. Applies when `pattern` is string type.
* @return {boolean} Returns `true` if `subject` matches `pattern` or `false` otherwise.
* @example
* as.matches('pluto', /plu.{2}/);
* // => true
*
* as.matches('sun', 'S', 'i');
* // => true
*
* as.matches('apollo 11', '\\d{3}');
* // => false
*/
export default function matches(subject, pattern, flags) {
const subjectString = coerceToString(subject);
const flagsString = coerceToString(flags);
let patternString;
if (!(pattern instanceof RegExp)) {
patternString = toString(pattern);
if (patternString === null) {
return false;
}
pattern = new RegExp(patternString, flagsString);
}
return pattern.test(subjectString);
}