You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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