String.split()
The JavaScript String.split() method allows you to split a string into an array of substrings.
The String.split()
method takes a String
object and converts it to an Array
of substrings that are split by a given separator.
String.split()
also allows you to limit the number of instances to be separated by defining a limit parameter
Syntax
str.split([separator[, limit]]);
Slicing a String
var str = "Welcome to Code Snippet."
str.slice(11, -1)
// returns "Code Snippet"
==NOTE: no
Splitting a string at each space
function strSplitter(str){
return str.split(' '); // This separates a string at each space
};
strSplitter('This is a string');
//returns ["This", "is", "a", "string"]
Splitting a string at each comma
function strSplitter(str){
return str.split(','); // This separates a string at each comma
};
strSplitter('Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday');
//returns ["Sunday", " Monday", " Tuesday", " Wednesday", " Thursday", " Friday", " Saturday"]
Splitting a string using a limit
function strSplitter(str){
return str.split('-', 3); // This separates a string at each hyphen, returning the first 3 items
};
strSplitter('8-0-8-5-5-5-1-2-3-4');
//returns ["8", "0", "8"]
Help us improve our content