EN
JavaScript - how to use Symbol.split method example?
3 points
Using JavaScript it is possible to split string with Symbol.split
(with splitter) in following way.
xxxxxxxxxx
1
var splitter = {
2
[Symbol.split] : function(text, limit) { // this function splits string by space
3
let result = [ ];
4
5
if (text.length > 0) {
6
let index = 0;
7
8
for (let i = 0; i < text.length; ++i) {
9
if(text[i] == ' ') {
10
result.push(text.substring(index, i));
11
12
index = i + 1;
13
}
14
}
15
16
result.push(text.substring(index));
17
}
18
19
return result;
20
}
21
};
22
23
// Example:
24
25
var text = 'This is some text...';
26
var array = text.split(splitter);
27
28
console.log(array);
Output (with NodeJS):
xxxxxxxxxx
1
[ 'This', 'is', 'some', 'text...' ]
Note:
Symbol.split
has been introduced in ES2015.