Bolli Bolli - 1 year ago 95
Javascript Question

parse jQuery like selector regex

I have the string


and i want to get

["foo", ".bar", "#baz"]

I tried doing it with

"".match(/[^.]+/g).join(' .').match(/[^#]+/g).join(' #').split(' ');

but i think it's way too long. Do you know any shorter version?


I don't want to get

["foo", "bar", "baz"]

what i could do with


Answer Source

You can use positive lookahead to split a string but keep the delimiting character.

var myString = "";
var myRegex = /(?=[\.#])/g;

The syntax for positive lookahead is (?=)