Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

string to regex javascript

function stringToRegex(s, m) {
  return (m = s.match(/^([/~@;%#'])(.*?)1([gimsuy]*)$/)) ? new RegExp(m[2], m[3].split('').filter((i, p, s) => s.indexOf(i) === p).join('')) : new RegExp(s);
}

console.log(stringToRegex('/(foo)?/bar/i'));
console.log(stringToRegex('#(foo)?/bar##gi')); //Custom delimiters
console.log(stringToRegex('#(foo)?/bar##gig')); //Duplicate flags are filtered out
console.log(stringToRegex('/(foo)?/bar')); // Treated as string
console.log(stringToRegex('gig')); // Treated as string
 Run code snippetHide results
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #string #regex #javascript
ADD COMMENT
Topic
Name
4+7 =