Home > Article > Web Front-end > Usage of split() method in js
split() method splits the string into an array according to the specified separator. The syntax is stringVariable.split(separator). It can be separated by characters, multiple characters or regular expressions, and the number of occurrences of the separator is specified. , ignore empty elements.
Usage of split() method in JS
What is the split() method?
The split() method is used to split a string into an array according to the specified delimiter (that is, to separate the string). It returns an array containing substrings separated by delimiters.
Syntax:
<code class="javascript">stringVariable.split(separator)</code>
Usage:
<code class="javascript">const str = "Hello World"; const arr = str.split(''); console.log(arr); // ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']</code>
<code class="javascript">const str = "Hello, World, Again"; const arr = str.split(', '); console.log(arr); // ['Hello', 'World', 'Again']</code>
<code class="javascript">const str = "1234567890"; const arr = str.split(/\d+/); console.log(arr); // ['', '1234567890', '']</code>
<code class="javascript">const str = "123,456,789"; const arr = str.split(',', 2); console.log(arr); // ['123', '456,789']</code>
<code class="javascript">const str = "Hello,,World, Again"; const arr = str.split(',').filter(elem => elem); console.log(arr); // ['Hello', 'World', 'Again']</code>
Note:
The above is the detailed content of Usage of split() method in js. For more information, please follow other related articles on the PHP Chinese website!