Home >Web Front-end >JS Tutorial >Usage of split() method in js

Usage of split() method in js

Charles William Harris
Charles William HarrisOriginal
2024-05-06 10:45:241001browse

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

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>
  • stringVariable: The string variable to be split.
  • separator: Separates strings, defaults to a space character.

Usage:

  1. Separated by characters:
<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>
  1. Separated by multiple characters:
<code class="javascript">const str = "Hello, World, Again";
const arr = str.split(', ');
console.log(arr); // ['Hello', 'World', 'Again']</code>
  1. Separated by regular expression:
<code class="javascript">const str = "1234567890";
const arr = str.split(/\d+/);
console.log(arr); // ['', '1234567890', '']</code>
  1. Specify the number of occurrences of the delimiter character:
<code class="javascript">const str = "123,456,789";
const arr = str.split(',', 2);
console.log(arr); // ['123', '456,789']</code>
  1. Ignore empty elements:
<code class="javascript">const str = "Hello,,World, Again";
const arr = str.split(',').filter(elem => elem);
console.log(arr); // ['Hello', 'World', 'Again']</code>

Note:

  • The delimiter can be any string or regular expression.
  • If the delimiter is not specified, the string is separated by spaces.
  • The split() method does not change the original string.
  • If the delimiter does not exist in the string, returns a single-element array containing the entire string.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn