You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
simple string regular expression that exposes matches in defined variables
install
node
$npminstallsregex
component
$componentinstalljwerle/sregex
bower
bowerinstallsregex
usage
using sregex is as simple as passing it a string
varregex=sregex('some string')regex.test('some string');// trueregex.test('some other string');// false
the returned regex object from sregex is an instance of RegExp with a parse() function attached to it
regex.parse('some string');// {}
you can easily define variables within your string sregex string and access them from a string with the parse function
varregex=sregex('my name is :name and i am :age');varvalues=regex.parse('my name is joe and i am 22');console.log(values.name);// joeconsole.log(values.age);// 22
the str argument for sregex accepts a string, but it also can have valid regular expression interpolated
varregex=sregex('it can accept multiple regular expressions like ([a-zA-Z]+), ([0-9]+), and ([a-z]+)');varvalues=regex.parse('it can accept multiple regular expressions like foogots, 45, and apple');console.log(values[0]);// foogotsconsole.log(values[1]);// 45console.log(values[2]);// apple
it can also accept an instance of `RegExp as input
varregex=sregex(/^foo\s?bar\s?([a-z]+)/);varvalues=regex.parse('foo bar noob');console.log(values[0]);// noob
building a regular expression router
building a router that parses url parameters can be simple as well
varhttp=require('http');varsregex=require('sregex');http.createServer(function(req,res){varregex=sregex('/:resource/:id/:action')// in the browser head to `https://localhost:4000/videos/1234/edit`console.log(regex.parse(req.url));// { resource: 'videos', id: '1234', action: 'edit' }}).listen(4000);
api
sregex(str)
converts a string to regular expression and allows retrieval of defined variables when parsing
str - a string to convert to regular expression
example
varregex=sregex('/user/:id')
.parse(str)
parses a given string and returns an object representing the values extracted using the regular expression used to create it
str - a string to parse and extact values from based on regular expression matches