JavaScript Split String: Dive into String Manipulation’s and More
JavaScript split string method splits a string object to an array of strings. This is by breaking up the string into substrings.. Wondering how to split the string in JavaScript? Here are the split js string methods, you’ll learn about in this post. Moreover, JS split method is pretty much like Java split method. Using JS split method, we can perform the following.What is the JavaScript split string method?
The JavaScript split() method splits a string object to an array of strings. the split method performs the following.- To split a string into an array of substrings.
- Returns a new array.
- It doesn’t change the original string.
Syntax of the JavaScript split method
Separator and Limit are two arguments that a split method can accept. Separator: It’s an optional argument. It defines the character or regular expression. If you don’t provide the separator character, it will return full string as an array. Limit: It’s an optional argument. It defines how many times to split a matched value. If the limit is not specified, it will split at all matched values and return an array. Note: In separator for an empty string (“”) declaration, the string splits between each character. In addition, there is a number of ways to split a string. So we are trying to cover different string methods implementation below. Also, note that the String replace method is different from the split method. Replace method can be leveraged when you want to replace a specific string.Split String Method Variations in JavaScript
Leveraging Split() method, we tried to cover numerous examples with JavaScript implementation. Here you go.split string by whitespace
Here is the JavaScript code to split string by whitespace.
var str = "Welcome To My Blog";
var re = str.split(" ");
console.log(re);
Result/Output
["Welcome", "To", "My", "Blog"];
By separator character and limit
Let’s create a script to split using separator and limit.var str2 = "example two of character class";
var re = str2.split(" ", 1);
console.log(re);
Result/Output
["example"]
JS string split by comma(CSV)
The following examples illustrate “How to create a split comma separated string using JavaScript”. Refer to the string input parameter and output field.
var myString = 'this,is,an,csv file';
var mySplits = myString.split(",");
console.log(mySplits);
Result/Output
[ "this", "is", "an", "csv file" ]
By slash using regular expression(regex) pattern
we can split string by slash by applying regular expression patterns. Refer to the below script for the string input parameter and output field.
var myString = 'this/is/slash';
var mySplits = myString.split(/[\\\/]/);
console.log(mySplits);
Result/Output
[ "this", "is", "slash" ]
Similarly vice versa in case you want to split using the backslash.
You may love,
Convert Java InputStream from File.
split string at index sequence
Following JavaScript split function example illustrates “how to split the string at index”.
function splitIndex(value, index) {
return value.substring(0, index) + "," +value.substring(index);
}
var result = splitIndex("3362174", 3);
console.log(result);
Result/Output
[336,2174]
Using regex(regular expression) pattern
We can str split by providing a regular expression pattern.
var date = "04-29-2017";
var mySplits = date.split(/[.,\/ -]/);
console.log(mySplits);
Result/Output
[ "04", "29", "2017" ]
By delimiters
var delimiter = "abcd+wxyz-ghi";
var separators = [' ', '\\\+', '-', '\\\(', '\\\)',
'\\*', '/', ':', '\\\?'];
console.log(separators.join('|'));
var result =
delimiter.split(new RegExp(separators.join('|'), 'g'));
console.log(result);
Result/Output
[ "abcd", "wxyz", "ghi" ]
With uppercase
var myString = 'HelloLetsSplitCharacterClass';
var mySplits = myString.split(/(?=[A-Z])/);
console.log(mySplits);
Result/Output
[ "Hello", "Lets", "Split", "Character", "Class" ]
Using the length method
var myString = "prototype,str,split,method";
var mySplits = myString.split(',').length;
console.log(mySplits);
Result/Output
4
To get the first element
var myString = "welcome_to_split function";
var mySplits = myString.split(/_(.+)/)[0];
console.log(mySplits);
Result/Output
welcome
The result/output seen using the string methodsJavaScript console log method or document write method.
Into array
In general, we create an array in our programming based on business logic. So here split() function convert a single string into an array of strings.
var arrayString = "Regular Expression";
var myArraySplits = arrayString.trim().split(" ");
console.log(myArraySplits);
Result/Output
[Regular,Expression]
If you are looking to parse JSON string into an array, the following example illustrates that.
Also for multiple strings, we can loop through the values with the split method.
var fullData ='{"fname":"Thomas","lname":"Cook","city":"Miami",
"state":"Florida", "Hobbies":"golf,trading,chess,fishing"}';
var data = JSON.parse(fullData);
var getHobbies = data.Hobbies;
var getHobbiesArray = getHobbies.split(",");
console.log(getHobbiesArray);
Result/Output
[golf,trading,chess,fishing]
Using the split function, we can parse the query string as well.
Into chunks
var myString = '0204161980';
var myChunkSplits = myString.match(/.{1,2}/g);
console.log(myChunkSplits);
Result/Output
["02", "04", "16", "19", "80"]
Convert string to a character array using the split js string method
var myString = "Hello JavaScript Array!";
var myCharacterSplit = myString.split('');
console.log(myCharacterSplit);
Result/Output
["H", "e", "l", "l", "o", " ", "J", "a",
"v", "a", "s", "c", "r","i", "p", "t"," ",
"A", "r", "r", "a","y","!"]
Using get element by id and split
In JavaScript, you can get element by id and split. Here is the sample javascript split function to split a string on the number of elements.
var myString = document.getElementById('node').value.trim( );
var myElementSplit = myString.split(/\s+/);
console.log(myElementSplit);
On a given index and return the values using the string split js method
The following JavaScript split function illustrates, How to split the string on the specified index and return the values by using the string split js method.
function splitString(value, index) {
return value.substring(0, index)+ "," +value.substring(index);
}
console.log(splitString("0123456", 2));
Result/Output
[01,23456]
Receiving error JavaScript split is not a function?
You might be experiencing error “TypeError: string.split is not a function”. This happens whenever you are calling .split() method on other than a string. The JS runtime won’t find the .split() method for that data type. for such scenarios, you must ensure to pass a string to your function. Here is an example:
var test = Hello Javascript;
result = test.split(" ");
console.log(result);
The above JavaScript snippet throws an error “TypeError: string.split is not a function”.
Since here we are trying to split the variable test ( Hello Javascript) which is not a string type.
The correct declaration of this split function should be as follows
var test = "Hello Javascript";
result = test.split(" ");
console.log(result);
So here we declared a variable test as a string (added string quotes “” to Hello JavaScript).
The result will be [Hello,JavaScript]
On newline
The following example will return an array of strings upon using the js split() method on the newline.
var arraytest = "cat\nrat";
result = arraytest.split("\n");
console.log(result);
Result/Output
["cat", "rat"]
split string to map method(using ES6 standard)
const string = "country:Finland, city:Helsiniki,";
const strvalue = string.split(",").map(pair=>pair.split(":"));
const result = new Map(strvalue);
console.log(result.get("country") );
Note: const is available in ES6 standard.
Result/Output
["Finland"]
Using reverse string
var result = 'reversestring'.split('').reverse().join('') ;
console.log(result);
Result/Output
["gnirtsesrever"]
Using the join method
var emailstr = "split@js_com,split2@js_com";
var emailarray = emailstr.split('_');
var result = emailarray.join('.');
console.log(result);
Result/Output
[[email protected],[email protected]]
On quotation marks
var text = "I would \"like\" to \"split string\".";
var result = text.split("\"");
console.log(result);
Result/Output
[I would ,like, to ,split a string,.]
On special character
var text = "i@like_special.character";
var result = text.split(/[.\@_]/);
console.log(result);
Result/Output
[i,like,special,character]
Want to deep dive into JavaScript programming language?
Looking for some Java articles, Check out here on Array List conversions.
To conclude, we have covered various JavaScript split string examples in this tutorial.
Happy Coding 🙂
Frequently Asked Questions (FAQs)
What is the JavaScript split string function?
The JavaScript split function divides a string into an array of substrings based on a specified separator.
How do you use the split function in JavaScript?
Use the split function by providing a separator string or regular expression. For example, ‘text.split(“,”)’ splits the string at each comma.
Can the split function in JavaScript handle regular expressions?
Yes, the split function can use regular expressions as a separator, allowing complex string splitting scenarios.
What happens if the separator is not found in the string?
If the separator is not found, split returns an array containing the original string as its only element.
Is it possible to limit the number of splits in JavaScript's split function?
Yes, you can limit splits by providing a second argument to the split function, specifying the maximum number of splits.
How does split handle empty strings in JavaScript?
If you split an empty string, JavaScript returns an empty array.
Can you use the split function to create an array of characters?
Yes, by using an empty string (”) as the separator, you can split a string into an array of its individual characters.
What is the difference between split and substring methods in JavaScript?
Split divides a string into an array of substrings, while substring extracts a specific portion of a string without creating an array.
How does the split function handle white spaces as separators?
When using white space (‘ ‘) as a separator, split will divide the string at each space, useful for separating words in a sentence.
Can split be used to reverse a string in JavaScript?
Indirectly, yes. You can split a string into characters, reverse the array, and then join it back into a string.