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']

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

相关推荐
小江的记录本19 分钟前
【AI大模型选型指南】《2026年5月(最新版)国内外主流AI大模型选型指南》(个人版)
前端·人工智能·后端·ai·aigc·ai编程·ai写作
@PHARAOH33 分钟前
HOW - 前端输入场景支持拼音匹配
前端
计算机安禾43 分钟前
【c++面向对象编程】第21篇:运算符重载基础:语法、规则与不可重载的运算符
java·前端·c++
__log1 小时前
Vue 3 核心技术深度解析:从“会用API“到“懂原理、能表达“
前端·javascript·vue.js
Asurplus1 小时前
【VUE】16、使用 wangEditor 富文本编辑器
vue.js·图片上传·wangeditor·富文本编辑器
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_52:(深入 XPathExpression 接口)
开发语言·前端·javascript·ui·html·音视频
不会写DN2 小时前
通过白名单解决 pnpm i 报错 Ignored build scripts
javascript·面试·npm
UXbot2 小时前
AI 原型工具零设计基础操作指南与功能解析(2026)
前端·ui·产品经理·原型模式·web app
yuzhiboyouye2 小时前
VO一般java后端怎么转换成前端想要的数据
java·前端·状态模式