js中常见切割截取字符串的几种方法小结

发布时间:2026-09-28 17:58:35 浏览次数:1

JS中常见切割截取字符串的几种方法小结

字符串是Web开发中不可或缺的一部分,而JavaScript(简称JS)中提供了许多操作字符串的方法。其中,切割和截取字符串在实际开发中非常常见。本文就来介绍一下JS中常见的切割和截取字符串的几种方法。

slice()

slice(start, end) 方法可以从一个字符串中提取一个子字符串,并返回新的字符串。该方法包含两个参数:起始索引(包括)和结束索引(不包括)。

const str = 'Hello, World!';// 从第7个索引(包括)开始提取字符串,到第13个索引(不包括)结束截取字符串const slicedStr = str.slice(7, 13);console.log(slicedStr); // World

在上面的示例中,从 start 索引 7 开始,提取字符串中索引 7-12 的字符,不包括索引 13 的字符。最终截取到的字符串是 World。

需要注意的是,如果未提供第二个参数,则 slice 方法会一直截取到字符串的最后一个字符。

const str = 'Hello, World!';// 从第7个索引(包括)开始提取字符串,一直截取到字符串结尾const slicedStr = str.slice(7);console.log(slicedStr); // World!

substring()

substring(start, end) 方法与 slice() 方法类似,但是 substring() 不允许使用负数作为参数。如果 start 和 end 参数中的任何一个为负数,则 substring() 方法会将其转换为 0。此外,如果 start 大于 end,则该方法会将两个参数交换,以此保证 start 在 end 之前。

const str = 'Hello, World!';// 从第7个索引(包括)开始提取字符串,到第13个索引(不包括)结束截取字符串const slicedStr = str.substring(7, 13);console.log(slicedStr); // World

需要注意的是,在 slice() 方法中可以使用负数作为参数提取字符串,而在 substring() 方法中不行。

substr()

substr(start, length) 方法从一个字符串中提取子字符串,并返回新的字符串。该方法包含两个参数:起始索引(包括)和要提取的字符数。

const str = 'Hello, World!';// 从第7个索引(包括)开始提取字符串,一共提取 5 个字符const slicedStr = str.substr(7, 5);console.log(slicedStr); // World

在上面的示例中,从 start 索引 7 开始,提取字符串中索引 7-11 的字符,共 5 个字符。最终截取到的字符串是 World。

需要注意的是,如果未提供第二个参数,则 substr 方法会一直截取到字符串的最后一个字符。

const str = 'Hello, World!';// 从第7个索引(包括)开始提取字符串,一直截取到字符串结尾const slicedStr = str.substr(7);console.log(slicedStr); // World!

split()

split(separator, limit) 方法将一个字符串分割成字串,将字串存储到数组中。该方法包含两个参数:分隔符和可选的截取字符串数量。

const str = 'How are you doing today?';// 使用空格分隔字符串,最多拆分 3 个子字符串const splitStr = str.split(' ', 3);console.log(splitStr); // [ 'How', 'are', 'you' ]

在上面的示例中,split() 方法使用空格作为分隔符,最多将字符串分成 3 个字串。最终存储在数组中的内容是 [ 'How', 'are', 'you' ]。

实例应用

通过以上的介绍,不难发现 slice()、substring()、substr() 和 split() 方法的作用有重叠的部分,但也各有特点。我们可以根据不同场景选择不同的方法。

例如,在开发Web应用过程中,经常需要从URL中获取参数。此时我们可以使用 split() 方法来将URL按照 ? 号和 & 号分隔开,然后再将获取到的参数以 = 号分隔提取出来。

const url = 'https://www.example.com/?name=John&age=30&gender=male';// 将URL按照 ? 和 & 号分隔开,获取参数对象const query = url.split(/[?&]/).slice(1).reduce((obj, item) => {  const [key, value] = item.split('=');  obj[key] = value;  return obj;}, {});console.log(query); // { name: 'John', age: '30', gender: 'male' }

总结

本文介绍了JS中常见切割和截取字符串的四种方法,它们分别是 slice()、substring()、substr() 和 split() 方法。在实际开发中,可以根据不同的场景选择不同的方法,从而更好地完成开发任务。

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477