提取子字符串的方法汇总

在 JavaScript 中,有多种方法可以提取子字符串。以下是常见的方法汇总:

1. substring

substring 方法用于提取字符串的某个部分,并返回一个新的字符串。它接受两个参数:起始索引和结束索引(不包括结束索引)。

javascript 复制代码
const str = "Hello, world!";
const result = str.substring(7, 12);
console.log(result); // "world"

2. slice

slice 方法与 substring 类似,但它可以接受负数索引,表示从字符串末尾开始计算。

javascript 复制代码
const str = "Hello, world!";
const result = str.slice(7, 12);
console.log(result); // "world"

const negativeResult = str.slice(-6, -1);
console.log(negativeResult); // "world"

3. substr

substr 方法用于从起始索引开始提取指定长度的子字符串。它接受两个参数:起始索引和长度。

javascript 复制代码
const str = "Hello, world!";
const result = str.substr(7, 5);
console.log(result); // "world"

4. split

split 方法主要用于分隔字符串,但它也可以用于提取子字符串。

javascript 复制代码
const str = "Hello, world!";
const result = str.split(" ")[1];
console.log(result); // "world!"

5. match

match 方法与正则表达式结合使用,可以提取符合模式的子字符串。

javascript 复制代码
const str = "Hello, world!";
const result = str.match(/world/);
console.log(result[0]); // "world"

6. replace with a function

replace 方法可以与正则表达式和回调函数结合使用,提取子字符串。(参考: replace的详解和常用的案例)

javascript 复制代码
const str = "Hello, world!";
const result = str.replace(/(world)/, (match) => match);
console.log(result); // "Hello, world!"

示例代码

以下是一个包含上述所有方法的示例代码:

javascript 复制代码
const str = "Hello, world!";

// 使用 substring 方法
const substringResult = str.substring(7, 12);
console.log(substringResult); // "world"

// 使用 slice 方法
const sliceResult = str.slice(7, 12);
console.log(sliceResult); // "world"

const negativeSliceResult = str.slice(-6, -1);
console.log(negativeSliceResult); // "world"

// 使用 substr 方法
const substrResult = str.substr(7, 5);
console.log(substrResult); // "world"

// 使用 split 方法
const splitResult = str.split(" ")[1];
console.log(splitResult); // "world!"

// 使用 match 方法
const matchResult = str.match(/world/);
console.log(matchResult[0]); // "world"

// 使用 replace 方法
const replaceResult = str.replace(/(world)/, (match) => match);
console.log(replaceResult); // "Hello, world!"

这些方法可以根据具体需求选择使用。slice 和 substring 方法是最常用的提取子字符串的方法,而 substr 方法在某些情况下也很有用。split、match 和 replace 方法提供了更强大的字符串处理能力。

相关推荐
qq_274475156 分钟前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
西西弗Sisyphus23 分钟前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 初识回调(5)
开发语言·c++
程序员小杰@32 分钟前
Java 统一报文转换 + 签名验签完整介绍
java·开发语言
Java后端的Ai之路2 小时前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
船神丿男人2 小时前
从爬楼梯到最小路径和:6 道 C++ 动态规划题的状态设计
开发语言·c++·动态规划
Evand J2 小时前
【MATLAB例程】基于多基站AOA与距离辅助的二维运动目标定位及速度估计,附下载链接
开发语言·matlab·距离·aoa·多基站
GuWenyue2 小时前
昵称限 20 字,8 个 emoji 却超长:一个「字」在系统里有四种长度
javascript·数据库·后端
数字供应链安全产品选型2 小时前
从自动化扫描到 AI 自主攻防:下一代渗透测试需要突破哪些核心技术?
开发语言·php
CV-deeplearning2 小时前
Chrome DevTools实战
前端·agent·chrome devtools·mcp
xurileidian2 小时前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法