String Split Method –
Based on the separator, passed to split(separator) will be breaking the string into substring where it matches.
It’s syntax look like –
Note: split method not change the original string in this process.
There is another parameter limit which is optional and it decides the number of splits in the string and returns a new array.
For more information about split string method click here.
let name = “Hi i am jsstartup”;
In the second step, create another variable array and assign a result return from the split method used on a name with blank space separator and limit two.
let array = name.split(” “, 2);
Any guess, what should be the output of above statement ?
Now, you know the answer is undefined but why it should be “jsstartup”. Let me explain –
So, we use a split method and passes two parameter, as separator which is ” “ blank space and limit which is 2.
After split, array variable holding only 3 element.
let array = [“Hi”, “i”, “am”];
Split Limit Parameter-
But where is “jsstartup” also? As we put limit 2 on the split method so it will break the string up to 2 matching substring. It’s like –
And due to limit, it only include “Hi”, “i” & “am”.
At last, That’s why we get an answer “undefined“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – new replaceAll method really replace all matching string
- JS Quiz – can it uppercase the string first letter
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.