Strings can be chopped and diced in many different ways in JavaScript, and for many different purposes. As a result, there are many different methods for dealing with strings, but slice
and split
are some of the most useful.
Split
Breaks a string into an array based on a particular character, or regular expression. This can be particularly useful when the character is already known, such as the slashes in a file path:
var filepath = "path/to/file.jpg";
console.log(filepath.split("/"));
> ["path", "to", "file.jpg"]
Or with comma-delimited data:
var commaData = "This,is,a,lot,of,data";
var dataRef = commaData.split(",");
console.log(dataRef.pop());
> ["data"]
An optional integer after the split character or regular expression will limit the size of the resulting array:
var lyrics = "You load sixteen tons what do you get";
var dataBreakdown = lyrics.split(" ",4);
console.log(dataBreakdown);
> ["You", "load", "sixteen", "tons"]
Slice
slice
extracts a portion of a string. It does so using a numerical index, with an optional termination point.
var birth = "I was born one mornin’ when the sun didn’t shine";
console.log(birth.slice(6);
> "born one mornin’ when the sun didn’t shine"
Note that the index of the first letter of the string is 0
, and that spaces are counted. Adding an optional terminator:
birth.slice(6,22);
> "born one mornin’"
slice()
does not affect the original string.
Using negative numbers with slice()
A negative value for the terminator counts from the end of the string:
var work = "I picked up my shovel and I walked to the mine";
work.slice(2,-25);
> "picked up my shovel"
That is, the slice extracts from the third character (keeping in mind that it indexes from 0), and stops at the 26th character from the end. Negative values can also be used for the initial value, making slice
operate from that end-point in the string to the very end:
var work = "I picked up my shovel and I walked to the mine";
work.slice(-20);
> "I walked to the mine"
If two negative numbers are used, slice
extracts from the end for both values:
work.slice(-20, -12);
> "I walked"
Photograph by Gabriel Amadeus, licensed under Creative Commons; lyrics from “Sixteen Tons” by “Tennessee” Ernie Ford.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.