提取子字符串的方法汇总

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

相关推荐
周杰伦fans2 小时前
Edge浏览器 about:blank 问题修复
前端·数据库·edge
嘉琪0012 小时前
Day6 完整学习包(async/await)——2026 0318
前端·javascript·学习
SameX2 小时前
我做了个本地优先的 iOS 足迹 App,上架后才发现:最难的根本不是地图,而是让轨迹活下来
前端
踩着两条虫2 小时前
AI 驱动的 Vue3 应用开发平台 深入探究(十八):扩展与定制之集成第三方库
前端·vue.js·agent
css趣多多2 小时前
# Vue 3 `<script setup>` 中变量声明的正确姿势:何时必须使用 `ref()`?
前端·javascript·vue.js
用户69371750013842 小时前
跟你唠唠!A2A协议来了,谁能拿下下一代手机系统的主动权?
android·前端·人工智能
@PHARAOH2 小时前
HOW - Go 开发入门(二)
开发语言·后端·golang
踩着两条虫2 小时前
AI 驱动的 Vue3 应用开发平台 深入探究(十七):扩展与定制之扩展 Provider 系统
前端·vue.js·agent
BUG?不,是彩蛋!2 小时前
从零到一掌握 K 线与技术指标:Java 实战教程 | MA, RSI, MACD 全解析
java·开发语言·spring boot·量化投资