提取子字符串的方法汇总

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

相关推荐
Z_W_H_几秒前
【C#】C#中值类型和引用类型参数传递的区别
开发语言·c#
Data_agent6 分钟前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
leiming68 分钟前
C++ 02 函数模板案例
开发语言·c++·算法
weixin_421585019 分钟前
PYTHON 迭代器1 - PEP-255
开发语言·python
Shaneyxs16 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(13)
前端
半山烟雨半山青17 分钟前
微信内容emoji表情包编辑器 + vue3 + ts + WrchatEmogi Editor
前端·javascript·vue.js
码途潇潇18 分钟前
Vue 事件机制全面解析:原生事件、自定义事件与 DOM 冒泡完全讲透
前端·javascript
zmirror20 分钟前
Monorepo 在 Docker 中的构建方案方案
前端
小新11020 分钟前
vs2022+Qt插件初体验,创建带 UI 界面的 Qt 项目
开发语言·qt·ui
摘星编程28 分钟前
Ascend C编程语言详解:打造高效AI算子的利器
c语言·开发语言·人工智能