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

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

相关推荐
广州华水科技3 分钟前
大坝安全监测解决方案:单北斗GNSS形变监测系统应用与维护
前端
星光开发者19 分钟前
基于决策树随机森林算法的小说推荐系统的设计与实现-计算机毕设【课程设计】78485
vue.js·算法·微信小程序·django·php·课程设计·express
yivifu1 小时前
中文古籍电子书注释集成
前端·javascript·python·beautifulsoup·epub
vx_Biye_Design1 小时前
springboot高校选课系统82776-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·课程设计·express
niyongsheng1 小时前
后端零改动,给若依换一套现代化前端
vue.js·开源·node.js
weixin_448290251 小时前
书庐开发实战教学
javascript·css·html
默_笙1 小时前
🛴 从散件到整机:DeepAgents 与 Agent 身上预留的那些"插槽"(前置介绍)
前端·javascript
zhangzeyuaaa2 小时前
深入理解 Ruby 运算符:本质、分类、坑点与重载实战
开发语言·前端·ruby
一木 之林2 小时前
DeepSeek Agent 开发(一)
开发语言·前端·javascript
树下水月3 小时前
Typora破解
linux·服务器·前端