forked from helpers/handlebars-helpers
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathregex.js
52 lines (47 loc) · 1.22 KB
/
regex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'use strict';
var util = { options: require('./utils/options') };
var helpers = module.exports;
const kindOf = require('kind-of');
/**
* Convert the given string to a regular expression.
*
* ```handlebars
* {{toRegex 'foo'}}
* <!-- results in: /foo/ -->
* ```
* @param {String} `str`
* @return {RegExp}
* @api public
* @example {{toRegex 'foo'}} -> /foo/
*/
helpers.toRegex = function(str, locals, options) {
var opts = util.options({}, locals, options);
return new RegExp(str, opts.flags);
};
/**
* Returns true if the given `str` matches the given regex. A regex can
* be passed on the context, or using the [toRegex](#toregex) helper as a
* subexpression.
*
* ```handlebars
* {{test 'bar' (toRegex 'foo')}}
* <!-- results in: false -->
* {{test 'foobar' (toRegex 'foo')}}
* <!-- results in: true -->
* {{test 'foobar' (toRegex '^foo$')}}
* <!-- results in: false -->
* ```
* @param {String} `str`
* @return {RegExp}
* @api public
* @example {{test 'foobar' (toRegex 'foo')}} -> true
*/
helpers.test = function(str, regex) {
if (typeof(str) !== 'string') {
return false;
}
if (kindOf(regex) !== 'regexp') {
throw new TypeError('expected a regular expression');
}
return regex.test(str);
};