简体   繁体   中英

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.

Use .split then .filter .

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM