Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.match() matches only some of an identical array of strings

I’m matching an array of strings against a regex:

for (let subject_index in subjects) {
      if (subjects[subject_index].match(/.*Overview of Investor.*/i)) {
        subjects.splice(subject_index, 1)
      }
    }

The array subjects contains nine identical strings, all of them Overview of Investor. When I run this loop, it correctly matches five of the strings and does not match on the other four, even though all the strings are identical. Am I missing something?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re editing the array while iterating over it, which can cause weird problems. You can do this in a better way with Array.filter.

subjects = subjects.filter(subject => !subject.match(/.*Overview of Investor.*/i));

This way, you are not editing the array while reading the elements.

Edit: As noted in the comments, this solution removes the matched strings, because that is what the original poster’s solution is trying to do. If you want to keep the matched strings, use

subjects = subjects.filter(subject => subject.match(/.*Overview of Investor.*/i));

This is the same code but without the exclamation point.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading