How to use RegEx In Javascript

In this approach, we use a regular expression (‘/\s+/’) to split the input string into an array of words. Using the filter() method we get the words that are greater in length than the k value.

Syntax:

let res = str.split(/\s+/).filter(word => word.length > k).join(" ");

Example: The below example uses RegEx to find words that are greater than the given length k in JavaScript.

Javascript




let str = "hello geeks for geeks is computer science portal";
let k = 4;
let res = str.split(/\s+/)
    .filter(word => word.length > k);
console.log(res.join(" "));


Output

hello geeks geeks computer science portal


JavaScript Program to Find Words which are Greater than given Length k

In JavaScript, to find words that are greater than the given length k, we need to split an array into words and then filter out words based on their lengths.

Table of Content

  • Using split and filter methods
  • Using forEach and an empty array
  • Using RegEx

Similar Reads

Using split and filter methods

In this approach, we split the input string into an array of words using the split() method and then filter the array to retrieve the words whose length is greater than the given value ‘k’ using the filter() method....

Using forEach and an empty array

...

Using RegEx

In this approach, we initialize an empty array and iterate over each word in the input string using forEach. For each of the words that is greater than the k value is pushed into the result array and printed as the output....