js字符串分割方法

  1. 使用split()方法

这可能是最常见的字符串分割方法,它使用指定的分隔符将字符串拆分为子字符串,并返回一个数组。例如:

复制代码
const str = 'Hello World';
const arr = str.split(' ');

console.log(arr); // ['Hello', 'World']
  1. 使用substring()方法

此方法从字符串中提取子字符串并返回。可以使用它来分割字符串,但它需要手动指定子字符串的开始和结束索引。例如:

复制代码
const str = 'Hello World';
const str1 = str.substring(0, 5);
const str2 = str.substring(6);

console.log(str1); // 'Hello'
console.log(str2); // 'World'
  1. 使用slice()方法

此方法也从字符串中提取子字符串并返回。它需要指定开始和结束索引,但可以使用负索引来从字符串的末尾计算索引。例如:

复制代码
const str = 'Hello World';
const str1 = str.slice(0, 5);
const str2 = str.slice(6);

console.log(str1); // 'Hello'
console.log(str2); // 'World'
  1. 使用RegExp正则表达式

使用正则表达式可以更灵活地分割字符串,可以基于任何模式对字符串进行拆分。例如:

复制代码
const str = '1,2,3,4,5';
const arr = str.split(/[ ,]/);

console.log(arr); // ['1', '2', '3', '4', '5']

这将使用逗号和空格作为分隔符将字符串拆分为子字符串。

相关推荐
江华森14 分钟前
Web 开发基础:HTTP 与 REST
前端·网络协议·http
IT_陈寒1 小时前
Redis的KEYS命令把我搞崩溃了,改用SCAN才活过来
前端·人工智能·后端
Jackson__1 小时前
为什么 Agent 越聊越慢?聊聊 Context(上下文)管理
前端·agent·ai编程
KaMeidebaby2 小时前
卡梅德生物技术快报|抗体合成:多肽抗体合成工程化方案:Nsp2 保守肽多抗制备与多维度验证
前端·网络·数据库·人工智能·算法
青禾网络2 小时前
前端做音画匹配这件事,我从"随机塞"到"AI 自动对齐"
前端·github
仙人球部落2 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
2601_963771372 小时前
Hardening Enterprise WordPress Sites Against REST API Leaks and Bad Headers
前端·windows·word·php
蓝银草同学3 小时前
Stream 实战:博客列表排序、过滤与分页(AI 辅助学习 Java 8)
java·前端·后端
2601_957190903 小时前
飞行影院安装施工指南:场地、动感系统与影片内容配套
大数据·前端·人工智能
爱折腾的小黑牛3 小时前
简记往来批量录入功能的实现:从文本到结构化数据
前端·算法