Home >Web Front-end >JS Tutorial >How to use split() function in js

How to use split() function in js

下次还敢
下次还敢Original
2024-05-06 11:15:241043browse

JavaScript split() function splits a string into an array according to the specified delimiter. It accepts two parameters: delimiter and limit number of results (optional). Returns an array containing split elements. Usage scenarios include splitting strings by spaces, characters, or regular expressions, and controlling the number of split results.

How to use split() function in js

JavaScript split() function usage

split() function is used to split characters The string is split into arrays based on the specified delimiter.

Syntax

<code class="js">split(separator, limit)</code>

Parameters

  • separator: Optional. Character or regular expression that separates strings. If omitted, any whitespace characters are used by default.
  • limit: Optional. Limits the maximum number of elements in the resulting array of splits. If omitted, all contents of the string are split.

Return value

Returns an array containing split string elements.

Usage

<code class="js">const str = "Lorem ipsum dolor sit amet";

// 使用空格字符分隔
const words = str.split();
console.log(words); // 输出:["Lorem", "ipsum", "dolor", "sit", "amet"]

// 使用逗号分隔
const numbers = "1,2,3,4,5";
const numbersArray = numbers.split(",");
console.log(numbersArray); // 输出:["1", "2", "3", "4", "5"]

// 使用正则表达式分隔
const sentence = "The quick brown fox jumps over the lazy dog";
const words = sentence.split(/\s+/);
console.log(words); // 输出:["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]

// 限制拆分结果数量
const hobbies = "Reading, Writing, Coding, Hiking, Photography";
const limitedHobbies = hobbies.split(",", 3);
console.log(limitedHobbies); // 输出:["Reading", "Writing", "Coding"]</code>

Note

  • If the delimiter appears at the beginning or end of the string, it will be ignored.
  • The empty string delimiter will split the string into an array of individual characters.

The above is the detailed content of How to use split() function 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