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

Javascript To Return an Array of Words Over a Certain Length

I need to return words from an string that are over a certain length and do this on 1 line of code.

Say I need to return all words over 2 chars in length…

So far I have…

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

const wordsOver2Chars = str => str.match(/\w+\s+(.{2,})/g);

console.log(
  wordsOver2Chars('w gh w qwe regh aerguh eriygarew  hw whio wh w')
);

This does not work.

str.match(/\w+\s+/g) will return an array of words but I cannot figure out how to add in the length limiter as well.

Using split(‘ ‘).match(\regExp) errors.

>Solution :

The \w metacharacter matches word characters. When you add a + sign to it, you are implying that you want a word character chain of length at least 1, if you add another \w in front of it, you get min length of 2. And so on and so forth.

const wordsOver2Chars = str => str.match(/\w\w\w+/g);

console.log(wordsOver2Chars('w gh w qwe regh aerguh eriygarew  hw whio wh w'));

This is probably the easiest to understand approach, you are matching a single wordcharacter, followed by another one, and then followed by a 1+ chain.

If you want to be technically correct you can use curly brackets to define the number of elements, (3 being min, and empty after a comma meaning not defined max)

const wordsOver2Chars = str => str.match(/\w{3,}/g);

console.log(wordsOver2Chars('w gh w qwe regh aerguh eriygarew  hw whio wh w'));
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