Split a string into an array in JavaScript (with jQuery helpers)
jQuery has no split function of its own: split is a method of every JavaScript string. jQuery helps with what comes after, such as iterating with $.each, but splitting is plain JavaScript and works the same with or without the library.
Basics
"red,green,blue".split(","); // ["red", "green", "blue"]
"red,green,blue".split(",", 2); // ["red", "green"] (limit)
"abc".split(""); // ["a", "b", "c"]
"no separator".split(","); // ["no separator"]
"".split(","); // [""] (one empty string, not an empty array)
Real input is messy
Users type "sql, jquery , css,,". Clean it in one pass:
function toList(text) {
return text.split(",")
.map(function (s) { return s.trim(); })
.filter(function (s) { return s !== ""; });
}
toList("sql, jquery , css,,"); // ["sql", "jquery", "css"]
// several possible separators: comma, semicolon or new line
"a; b\nc,d".split(/[;,\n]+/).map(s => s.trim()); // ["a", "b", "c", "d"]
A regular expression separator accepts alternatives and repeated separators at once. If the regular expression contains capturing parentheses, the captured separators are included in the result, which is rarely wanted; use (?:…) groups.
With values from ASP.NET controls
<asp:TextBox ID="txtTags" runat="server" placeholder="e.g. sql, jquery, css" />
<ul id="tagPreview"></ul>
<script>
$(function () {
$("#<%= txtTags.ClientID %>").on("input", function () {
var $list = $("#tagPreview").empty();
$.each(toList($(this).val()), function (i, tag) {
$("<li>").text(tag).appendTo($list); // .text() keeps user input as text
});
});
});
</script>
$.each(array, function (index, value) { … }) passes the index first, unlike the native forEach(function (value, index) { … }). Building elements with .text() avoids injecting HTML from the user's input.
Splitting on the server too
The posted text box value must be split and validated again in C#:
string[] tags = txtTags.Text
.Split(new[] { ',', ';', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim())
.Where(t => t.Length > 0 && t.Length <= 30)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(10)
.ToArray();
On .NET 5 and later, StringSplitOptions.TrimEntries trims at the same time. Splitting a date into its parts is a special case that deserves parsing instead: Split a date into day, month and year.
Common mistakes
- Expecting an empty array from
"".split(","): it returns[""]. Filter empty entries as shown above. - Splitting CSV lines with
split(","): quoted fields containing commas break it. Use a CSV parser for real files. - Using
split(".")to get a file extension when names contain several dots: take the last element with.pop(), and handle names without any dot. - Forgetting that
splitwith a string separator is case-sensitive; use a regular expression with theiflag for case-insensitive separators.
Official documentation
- MDN: String.prototype.split(), Array.prototype.filter()
- jQuery API: jQuery.each()
- Microsoft Learn: String.Split, StringSplitOptions