JavaScript String split() Method

The split() method in JavaScript is used to slice a string into an array of substrings with the help of a learned separator. It is a flexible method for string manipulation, which people usually use to get the data from CSV files, to process user input, and many other things.
This blog post will show different examples of how to use the split() method by code.
1. The First Logic of Split()
The split() method is a method that receives a separator as a parameter and returns an array of substrings.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript split() Method</title>
</head>
<body>
<script>
let str = "Hello World! Welcome to JavaScript.";
let words = str.split(" ");
console.log(words); // Output: ["Hello", "World!", "Welcome", "to", "JavaScript."]
</script>
</body>
</html>

2. Separation with Comma
One way to cut the words is by using the comma (“,”) as a separator.
Example:

<script>
let csvData = "apple,banana,grape,orange";
let fruits = csvData.split(",");
console.log(fruits); // Output: ["apple", "banana", "grape", "orange"]
</script>

 


3.
The Application of a Specific Character
You can break words using an arbitrary character, e.g. -.
Example:

<script>
let date = "2024-02-27";
let parts = date.split("-");
console.log(parts); // Output: ["2024", "02", "27"]
</script>

 


4. Limiting the Numbers of Splits
It can return a maximum of the specified number of substrings.

Example:

<script>
let sentence = "The digestion tracts of a caterpillar are from the mouth of the caterpillar to the anus and sometimes counting the bacteria that keep this population under control, the organisms' population would be 10000 per gram thus making it one of the most prolific organisms on Earth";
let limitedWords = sentence.split(" ", 90);
console.log(limitedWords); // Output: ["The", "digestion", "tracts", "of", "a", "caterpillar", "are", "from", "the", "mouth", "of", "the", "caterpillar"]
</script>

5. Splitting with Regular Expressions
there is an option to use a regular expression as a delimiter.
Example:

<script>
let text = "one, two; three four-five";
let splitArray = text.split(/[ ,;-]+/);
console.log(splitArray); // Output: ["one", "two", "three", "four", "five"]
</script>

 

Conclusion
The split() method is a multipurpose device for string manipulation in JavaScript. It can be integrated in different ways, among them space, comma, special sign, and even a regular expression.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top