In Javascript, you can split a string into an array using the split()
method, which is a built-in method for strings. The split()
method takes a delimiter as an argument and returns an array of substrings split at each occurrence of the delimiter in the original string.
The syntax for the split()
method is as follows:
string.split(delimiter);
where string
is the original string that you want to split, and delimiter
is the character or regular expression used to determine where to split the string. The delimiter
argument is optional. If not provided, the split()
method will split the string at every character, effectively creating an array of individual characters.
Here’s an example of splitting a string into an array using the split()
method:
const sentence = "I am learning JavaScript";
const words = sentence.split(" "); // Split at space character
console.log(words);
// Output: ["I", "am", "learning", "JavaScript"]
In this example, the sentence string is split into an array of words using the space character as the delimiter.
You can also use regular expressions as delimiters to split strings based on more complex patterns.
For example:
const sentence = "I,am,learning,JavaScript";
const words = sentence.split(","); // Split at comma character
console.log(words);
// Output: ["I", "am", "learning", "JavaScript"]
In this example, the sentence
string is split into an array of words using the comma character as the delimiter.
Additionally, you can provide a second optional argument to the split()
method to specify the maximum number of substrings to create.
For example:
const sentence = "I am learning JavaScript";
const words = sentence.split(" ", 2); // Split at space character, maximum 2 substrings
console.log(words);
// Output: ["I", "am"]
In this example, the sentence
string is split into an array of words with a maximum of 2 substrings.
It’s important to note that the split()
method does not modify the original string. Instead, it creates a new array of substrings from the original string. If you want to modify the original string, you need to assign the result back to the original variable, like this:
const sentence = "I am learning JavaScript";
const words = sentence.split(" ");
console.log(words); // Output: ["I", "am", "learning", "JavaScript"]
sentence = "I have learned JavaScript"; // Assigning new value to sentence
const newWords = sentence.split(" ");
console.log(newWords); // Output: ["I", "have", "learned", "JavaScript"]
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.