Regex Favs

These are some of my favorite Regular Expressions to use. Code samples are Javascript. Usually I will use combinations of these to get the results I'm looking for. Right now I only have a few, plan on adding more as I come across em & write em.


Character Removal/Manipulation

Non-ASCII Characters

javascripts = s.replace(/[^\x{21}-\x{7E}\s\t\n\r]/g,'');

Control Characters

javascripts = s.replace(/[:cntrl:]/g,'');

Multi Spaces to Single

javascriptvar s = 'aaaa \t\r\nbbbb cccc \n\t ddd\n\n\n';
s = s.replace(/[\s+]/g,' ');

Start & End Spacing

javascrirptvar s = ' something ';
s = s.replace(/^[\ \t]+|[\ \t]+$/g,'');

Query String

javascriptvar s = 'https://a.b/?regex=stripquerystring';
s = s.replace(/^(.+)(\?.*)$/gm,'$1');


Video ID

javascriptvar s = '',
vid = s.replace(/(.*?)(^|\/|v=)([a-z0-9_-]{11})(.*)?/gi,'$3');

Valid Video Link

javascriptvar s = '',
valid = /^(.+)?(https?\:\/\/)(www\.)?(youtu\.?be\/?)(\.com\/)?(watch|embed)?.+?([a-z0-9_-]{11})(.+)?$/gim.test(s);

More by Aaron

Lisa Posts By Lisa
Aaron Posts By Aaron