OneCompiler

Is there a way to cut a string into words in JavaScript

I like to cut my string into an array of words. Is there a function to do so?

1 Answer

5 years ago by

You can use split() method of a string. You can provide a seperator to the split() method which splits the string based on the seperator provided. Check below, hope this helps!

let str = "Hello world! Happy Learning!";

/*  splits based on white space  */
console.log(str.split(" "));  // prints [ 'Hello', 'world!', 'Happy', 'Learning!' ]

/*  splits based on !   */
console.log(str.split("!")); // prints [ 'Hello world', ' Happy Learning' ]
5 years ago by Divya