Open In App

Lodash _.words() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.words() method is used to split the given string into an array of words. A pattern can be specified so that certain words can be removed from the string.

Syntax:

_.words(string, pattern);

Parameters:

  • string: It is the string that is to be split. The default value is an empty string.
  • pattern: It is a pattern on the basis of which the words would be matched. It is an optional parameter.

Return Value:

This method returns an array of words according to the pattern.

Example 1: In this example, we are converting a string into arrays of words by the use of the lodash _.words() method.

Javascript




// Defining Lodash variable
const _ = require('lodash');
 
// Specify the string to split
let str = "Geeks for Geeks";
 
// Using _.words() method
console.log(_.words(str));


Output:

[ 'Geeks', 'for', 'Geeks' ]

Example 2: In this example, we are converting a string into arrays of words by the use of the lodash _.words() method.

Javascript




// Defining Lodash variable
const _ = require('lodash');
 
// Specify the string to split
let str = "Geeks for Geeks";
 
// Using _.words() method
console.log(_.words(str, "for"));


Output:

[ 'for', index: 6, input: 'Geeks for Geeks', groups: undefined ]

Example 3: In this example, we are converting a string into arrays of words by the use of the lodash _.words() method.

Javascript




// Defining Lodash variable
const _ = require('lodash');
 
// Specify the string to split
let str = "& Geeks for Geeks &";
 
// Using _.words() method with
// a given pattern
console.log(_.words(str, /[^, ]+/g));


Output:

[ '&', 'Geeks', 'for', 'Geeks', '&' ]


Last Updated : 31 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads