Is it possible to loop through a RegEx range using Javascript

I thought to myself: is it possible to iterate over a RegEx range in JavaScript. Let's say for example I wanted to skip every letter of the alphabet, I could do something like this:

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

      

Note that I know I could do this using an .split()

in line and then a loop, but anyway I was wondering if I could use a RegEx range instead of a line, 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
}

      

This is just what I was interested in. If it's a stupid question, say so and I'll delete it.

+3


source to share


2 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 a new regex for each letter, which will have some overhead. If you do it like in this link: http://jsperf.com/regex-vs-split/2 its clearly better than split. This may not be the same with every language, but it seems to be in JS.

+3


source


You cannot iterate over a regular expression. The regex can be matched or tested against a string, but without a string there is no result.



0


source







All Articles