Skip to main content

Command Palette

Search for a command to run...

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

Published
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.
D

Thanks for sharing ! 👏

More from this blog

Stuff I Learned

17 posts

I'm a full stack developer, musician, and educator living in Minneapolis.