index.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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;