Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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...

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use .split then .filter.

console.log('w gh w qwe regh aerguh eriygarew  hw whio wh w'.split(" ").filter(word => word.length > 2))

about 4 years ago · Juan Pablo Isaza Report

0

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'));

about 4 years ago · Juan Pablo Isaza Report

0

Do you need to use regex? The easiest way would be to do

const wordsOver2Chars = s => s.split(' ').filter(w => w.length > 2).join(' ');

Split the string at ' ', then filter the resulting array to only contain words with length > 2 and join them again.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!