Search results
Results from the WOW.Com Content Network
split() method in JavaScript is used to convert a string to an array. It takes one optional argument, as a character, on which to split. In your case (~). If splitOn is skipped, it will simply put string as it is on 0th position of an array.
"my, tags are, in here".split(", ") with the splitting sequence swapped will at least split your original string in three parts, after each comma-and-space. If you do want five parts, the answers below specify the match string as a regular expression matching a space or a comma.
@BrodaNoel you're correct that's the one major caveat of the first code example. In that particular case it's best to use a character that is safe to split on, in my example the intent was to replace the , so it was "safe" but it certainly is something to be mindful of.
Javascript's String.split unfortunately has no way of limiting the actual number of splits. It has a second argument that specifies how many of the actual split items are returned, which isn't useful in your case.
See also How to split a long array into smaller arrays and Split javascript array in chunks using underscore.js (as well as many of the dupes in the linked questions) – Bergi Commented Jul 18, 2015 at 23:45
I am trying to solve a math problem where I take a number e.g. 45, or 111 and then split the number into separate digits e.g. 4 5 or 1 1 1. I will then save each number to a var to run a method on....
But, generically speaking .split(',').pop() works for last element on comma separated string. Just sayin' cuz I was misled by Guffa's awesome answer, I just disregarded it because didn't need a regex and thought the trick was there!
@bažmegakapa: Yeah, that's a matter of preference. The + '' is a pretty common trick for string coercion, but some people prefer the toString() method.
javascript split() regex Hot Network Questions Could probability amplitude for a path equal a complex number whose length is always 1 and whose angle is the action divided by Planck's constant?
My two cents, adding trim to remove the initial whitespaces left in sAc's answer. var str = 'Hello, World, etc'; var str_array = str.split(','); for(var i = 0; i < str_array.length; i++) { // Trim the excess whitespace.