DEV Community

Randy Rivera
Randy Rivera

Posted on

Split a String into an Array Using the split Method

  • The split method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.

  • Ex: Here we use split one string by spaces, then another by digits using a regular expression:

let str = "Hello Alan";
let byWords = str.split(" ");

let otherString = "=Wanna9play7rocket2league";
let byDigits = otherString.split(/\d/);

// byWords would have the value ["Hello", "Alan"]
// byDigits would have the value ["Wanna", "play", "rocket", "league"]
Enter fullscreen mode Exit fullscreen mode
  • Now let's use the split method inside the splitify function to split str into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
function splitify(str) {
  // Only change code below this line


  // Only change code above this line
}
splitify("Hello World,I-am code");
Enter fullscreen mode Exit fullscreen mode
  • A simple regular expression can be used to achieve this result.
  • /\W/ Matches any non-word character. This includes spaces and punctuation, but not underscores. It’s equivalent to /[^A-Za-z0-9_]/

  • Answer:

function splitify(str) {
return str.split(/\W/)

}
console.log(splitify("Hello Randy, I-am playing video games"));
// would return ["Hello", "Randy", "I", "am", "playing", "video", "games"]
Enter fullscreen mode Exit fullscreen mode

Larson, Quincy, editor. “Split a String into an Array Using the split Method.” https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method, Class Central, 2014, twitter.com/ossia.

Top comments (1)

Collapse
 
kamonwan profile image
Kamonwan Achjanis

Here is the better way that supports complex punctuation and I18n:
dev.to/kamonwan/the-right-way-to-b...