Home > Web Front-end > JS Tutorial > body text

How to use split() function in js

下次还敢
Release: 2024-05-06 11:15:24
Original
788 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!