TIL: convert a string into an array of words in JS


1 min read

Sometimes it's nice to document the little wins. Today, I learned this useful bit of code to parse a string into an array of words, while removing punctuation.

text.replace(/\p{P}/gu, "").split(" "))

To break this down:

  • text: the string to parse
  • .replace: a JavaScript function
  • /\p{P}/gu, "": regex that informs replace to remove all punctuation and replace it with nothing
  • .split(" "): a JavaScript function that breaks a string into an array based on the character passed into the function. In this case, it will split the string whenever there is a space.