Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to loop through a RegEx Range using Javascript

I was thinking to myself, is it possible to loop through a RegEx range in JavaScript. Say for instance I wanted to loop through each letter of the alphabet, I could do something like this:

var theAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
[].forEach.call(theAlphabet, function (a) {
    console.log(a);
});

Please note that I know I could have done this by using .split() on the string and then looping, but anyway I was wondering if instead of a string I could a use a RegEx range, something like this (I know it doesn't work)

var reg = new RegExp(/A-Z/), result;
while((result = reg.exec(reg)) !== null) {
    console.log(result); // ["A-Z", index: 1, input: "/A-Z/"] - Not correct I realise
}

It's just something I was wondering. If this is a silly question say so and I shall remove it.

like image 496
Mike Sav Avatar asked Nov 05 '25 14:11

Mike Sav


1 Answers

The question is rather unclear but I think you are asking if you can replace split with RegEx. You CAN do this of course, but two things come to mind.

You keep calling new regex for each letter which is going to have some performance overhead. If you do it like in this link: http://jsperf.com/regex-vs-split/2 its obviously better than split. This may not be the same with every language but it seems to be in JS.

like image 152
John Avatar answered Nov 08 '25 10:11

John