Bolli Bolli - 2 months ago 22
Javascript Question

parse jQuery like selector regex

I have the string

"foo.bar#baz"


and i want to get

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


I tried doing it with

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


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

PS:

I don't want to get

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


what i could do with

"foo.bar#baz".match(/[.#]+/g);

Answer

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

var myString = "foo.bar#baz";
var myRegex = /(?=[\.#])/g;
console.log(myString.split(myRegex));

The syntax for positive lookahead is (?=)