JSFiddle - React, Tailwind, and code Playground

by Chase Wilson

JavaScript

/**
 * Normalize the given path string,
 * returning a regular expression.
 *
 * An empty array should be passed,
 * which will contain the placeholder
 * key names. For example "/user/:id" will
 * then contain ["id"].
 *
 * @param  {String} path
 * @param  {Array} keys
 * @return {RegExp}
 * @api private
 */

function normalizePath(path, keys) {
  path = path
    .concat('/?')
    .replace(/\/\(/g, '(?:/')
    .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, parse)
    .replace(/([\/.])/g, '\\$1')
    .replace(/\*/g, '(.+)')
  
  function parse ( _, slash, format, key, capture, optional ) {
      keys.push(key);
      slash = slash || '';
      return ''
      + (optional ? '' : slash)
      + '(?:'
      + (optional ? slash : '')
      + (format || '') + (capture || '([^/]+?)') + ')'
      + (optional || '');
  }

  return new RegExp('^' + path + '$', 'i');
}


console.log(normalizePath('/something/:id',[]))