index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var extend = require('extend-shallow');
  3. /**
  4. * The main export is a function that takes a `pattern` string and an `options` object.
  5. *
  6. * ```js
  7. & var not = require('regex-not');
  8. & console.log(not('foo'));
  9. & //=> /^(?:(?!^(?:foo)$).)*$/
  10. * ```
  11. *
  12. * @param {String} `pattern`
  13. * @param {Object} `options`
  14. * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`.
  15. * @api public
  16. */
  17. function toRegex(pattern, options) {
  18. return new RegExp(toRegex.create(pattern, options));
  19. }
  20. /**
  21. * Create a regex-compatible string from the given `pattern` and `options`.
  22. *
  23. * ```js
  24. & var not = require('regex-not');
  25. & console.log(not.create('foo'));
  26. & //=> '^(?:(?!^(?:foo)$).)*$'
  27. * ```
  28. * @param {String} `pattern`
  29. * @param {Object} `options`
  30. * @return {String}
  31. * @api public
  32. */
  33. toRegex.create = function(pattern, options) {
  34. if (typeof pattern !== 'string') {
  35. throw new TypeError('expected a string');
  36. }
  37. var opts = extend({}, options);
  38. if (opts && opts.contains === true) {
  39. opts.strictNegate = false;
  40. }
  41. var open = opts.strictOpen !== false ? '^' : '';
  42. var close = opts.strictClose !== false ? '$' : '';
  43. var endChar = opts.endChar ? opts.endChar : '+';
  44. var str = pattern;
  45. if (opts && opts.strictNegate === false) {
  46. str = '(?:(?!(?:' + pattern + ')).)' + endChar;
  47. } else {
  48. str = '(?:(?!^(?:' + pattern + ')$).)' + endChar;
  49. }
  50. return open + str + close;
  51. };
  52. /**
  53. * Expose `toRegex`
  54. */
  55. module.exports = toRegex;