提取子字符串的方法汇总

在 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 方法提供了更强大的字符串处理能力。

相关推荐
DianSan_ERP16 分钟前
电商架构演进:如何在高并发场景下实现多平台API的标准化履约?
运维·前端·网络·安全·架构·自动化
殳翰18 分钟前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
落寞的星星1 小时前
这个对象就包含了已经转换好的DFA和各种词法分析器运转所需要的参数。下一步,我们就可以用ScannerInfo对象创建出Scanner对象,请看下面的代码:
开发语言·c#
nothing&nowhere1 小时前
用 Python 做问卷数据清洗:无效样本检测与处理实战
开发语言·python·数据清洗·数据处理·问卷星·问卷星脚本·刷问卷
2601_961593422 小时前
Rust 开发环境配置繁琐?RustRover 开箱即用搞定编码调试
开发语言·后端·macos·rust
HZZD_HZZD2 小时前
DL/T 645-2026新国标深度解读与智能电表协议适配实战:从帧结构变化到Java采集器升级的全链路改造方案
java·开发语言
碎_浪3 小时前
给键盘党的英语记忆工具:我做了一款「打字背单词」桌面应用
前端·程序员·ai编程
阿成学长_Cain4 小时前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
多加点辣也没关系4 小时前
JavaScript|第4章:类型转换
开发语言·javascript
聪慧的水蜜桃4 小时前
【YFIOs】用C#开发硬件之设备上云
开发语言·c#