Apa itu split di javascript?



Description

This method splits a String object into an array of strings by separating the string into substrings.

Syntax

Its syntax is as follows −

string.split([separator][, limit]);

Argument Details

  • separator − Specifies the character to use for separating the string. If separator is omitted, the array returned contains one element consisting of the entire string.

  • limit − Integer specifying a limit on the number of splits to be found.

Return Value

The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array.

Example

Try the following example.

<html>
   <head>
      <title>JavaScript String split() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = "Apples are round, and apples are juicy.";
         var splitted = str.split(" ", 3);
         document.write( splitted );
      </script>      
   </body>
</html>

Output

Apples,are,round, 

javascript_strings_object.htm

In this tutorial, we will learn about the JavaScript String split() method with the help of examples.

The split() method divides a string into a list of substrings and returns them as an array.

Example

const message = "JavaScript::is::fun";

// divides the message string at :: let result = message.split("::");

console.log(result); // Output: [ 'JavaScript', 'is', 'fun' ]


split() Syntax

The syntax of split() is:

str.split(separator, limit)

Here, str is a string.


split() Parameter

The split() method takes in:

  • separator (optional) - The pattern (string or regular expression) describing where each split should occur.
  • limit (optional) - A non-negative integer limiting the number of pieces to split the given string into.

split() Return Value

  • Returns an Array of strings, split at each point where the separator occurs in the given string.

Note: The split() method does not change the original string.


Example: Using split()

console.log("ABCDEF".split("")); // [ 'A', 'B', 'C', 'D', 'E', 'F' ]

const text = "Java is awesome. Java is fun.";

let pattern = "."; let newText = text.split(pattern);

console.log(newText); // [ 'Java is awesome', ' Java is fun', '' ] let pattern1 = ".";

// only split string to maximum to parts let newText1 = text.split(pattern1, 2);

console.log(newText1); // [ 'Java is awesome', ' Java is fun' ] const text2 = "JavaScript ; Python ;C;C++";

let pattern2 = ";"; let newText2 = text2.split(pattern2);

console.log(newText2); // [ 'JavaScript ', ' Python ', 'C', 'C++' ] // using RegEx

let pattern3 = /\s*(?:;|$)\s*/; let newText3 = text2.split(pattern3);

console.log(newText3); // [ 'JavaScript', 'Python', 'C', 'C++' ]

Output

[ 'A', 'B', 'C', 'D', 'E', 'F' ]
[ 'Java is awesome', ' Java is fun', '' ]
[ 'Java is awesome', ' Java is fun' ]
[ 'JavaScript ', '  Python ', 'C', 'C++' ]
[ 'JavaScript', 'Python', 'C', 'C++' ]

Note: If the separator is a regular expression with capturing parentheses, then each time the separator matches, the results of the capturing parentheses are spliced into the output array.


Recommended Reading: JavaScript Array join()

If you need to split up a string into an array of substrings, then you can use the JavaScript split() method.

In this article, I will go over the JavaScript split() method and provide code examples.

Basic Syntax of the split() method

Here is the syntax for the JavaScript split() method.

str.split(optional-separator, optional-limit)

The optional separator is a type of pattern that tells the computer where each split should happen.

The optional limit parameter is a positive number that tells the computer how many substrings should be in the returned array value.

ADVERTISEMENT

JavaScript split() method code examples

In this first example, I have the string "I love freeCodeCamp". If I were to use the split() method without the separator, then the return value would be an array of the entire string.

const str = 'I love freeCodeCamp';

str.split();
// return value is ["I love freeCodeCamp"]

Examples using the optional separator parameter

If I wanted to change it so the string is split up into individual characters, then I would need to add a separator. The separator would be an empty string.

const str = 'I love freeCodeCamp';

str.split('');
// return value ["I", " ", "l", "o", "v", "e", " ", "f", "r", "e", "e", "C", "o", "d", "e", "C", "a", "m", "p"]

Notice how the spaces are considered characters in the return value.

If I wanted to change it so the string is split up into individual words, then the separator would be an empty string with a space.

const str = 'I love freeCodeCamp';

str.split(' ');
// return value ["I", "love", "freeCodeCamp"]

ADVERTISEMENT

Examples using the optional limit parameter

In this example, I am going to use the limit parameter to return an array of just the first word of the sentence "I love freeCodeCamp".

const str = 'I love freeCodeCamp';

str.split(' ',1);
// return value ["I"]

If I change the limit to be zero, then the return value would be an empty array.

const str = 'I love freeCodeCamp';

str.split(' ',0);
//return value []

Should you use the split() method to reverse a string?

The reverse a string exercise is a very popular coding challenge.  One common way to solve it involves using the split() method.

In this example, we have the string "freeCodeCamp".  If we wanted to reverse the word, then we can chain together the split(), reverse() and join() methods to return the new reversed string.

const str = 'freeCodeCamp';

str.split('').reverse().join('');
//return value "pmaCedoCeerf"

The .split('') portion splits up the string into an array of characters.

The .reverse() portion reverses the array of characters in place.

The .join('') portion joins the characters together from the array and returns a new string.

This approach seems to work fine for this example. But there are special cases where this would not work.

Let's take a look at the example provided in the MDN documentation.

If we tried to reverse the string "mañana mañana", then it would lead to unexpected results.

const str = 'mañana mañana'
const reversedStr = str.split('').reverse().join('')

console.log(reversedStr)
// return value would be "anãnam anañam"

Notice how the tilde(~) is placed over the letter "a" instead of "n" in the reversed word. This happens because our string contains what is called a grapheme.

A grapheme cluster is a series of symbols combined to produce one single character that humans can read on screen. When we try to reverse the string using these types of characters, the computer can misinterpret these characters and produce an incorrect version of the reversed string.

If we just isolate the split method, you can see how the computer is breaking up each individual character.

const str = 'mañana mañana'

console.log(str.split(''))
//["m", "a", "ñ", "a", "n", "a", " ", "m", "a", "n", "̃", "a", "n", "a"]

There are packages that you can use in your projects to fix this issue and reverse the string correctly if you are using these special characters.

ADVERTISEMENT

Conclusion

The JavaScript split() method is used to split up a string into an array of substrings.

Here is syntax for the JavaScript split() method.

str.split(optional-separator, optional-limit)

The optional separator is a type of pattern that tells the computer where each split should happen.

The optional limit parameter is a positive number that tells the computer how many substrings should be in the returned array value.

You could use the split method to reverse a string, but there are special cases where this would not work. If your string contains grapheme clusters, then the result might produce an incorrectly reversed word.

You could also choose to use the spread syntax to split up the string before reversing it.

const str = 'mañana mañana'
console.log([...str].reverse().join(""))

I hope you enjoyed this article and best of luck on your JavaScript journey.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started