JavaScript如何截取指定位置的字符串

1,217 阅读2分钟

我们在日常开发中,经常需要对字符串进行删除截取增加的操作,我们这次说一下使用JavaScript截取指定位置的字符串。

一、使用slice()截取

slice()方法可以通过指定的开始和结束位置,提取字符串的某个部分,并以新的字符串返回被提取的部分。它的参数有两个,start和end。
start是必须填写的参数,规定从何处开始选取,如果是负数,就是从尾部倒着开始算。 end是可选填写的参数,规定从何处结束选择,如果没有指定end的值的话,只有start,那么就是默认从start一直截取到结束的所有字符,如果end的值是负数,也是从尾部倒着开始算。

以下是代码示例及输出结果:

var str = 'abcd9999';
var newStr = str.slice(2);
console.log(newStr); // 输出 cd9999;
newStr = str.slice(-2);
console.log(newStr); // 输出 99;
newStr = str.slice(2,4);
console.log(newStr); // 输出 cd;
newStr = str.slice(2,-2);
console.log(newStr); // 输出 cd99;

二、使用substring()截取

substring()方法用于提取字符串中介于两个指定下标之间的字符。
它有两个参数,start和stop。
start是必须填写的参数,并且start不能为负,这是和slice()方法不同的地方。 stop是可选填写的参数,并且stop也不能为负。
该函数返回一个新字符串,该字符串是一个子字符串,其内容是start处到stop-1处的所有字符,其长度为stop减start。

以下是代码示例及输出结果:

var str = 'Hello Word!';
var newStr = str.substring(2);
console.log(newStr); // 输出 llo Word!
newStr = str.substring(2,8);
console.log(newStr); // 输出 llo Wo

三、使用substr()截取\

substr方法用于返回一个从指定位置开始的指定长度的子字符串。
它也有两个参数,start和length。
start是必须填写的参数,它是指定所需的字符串的起始位置,可以是负数,负数效果同上面两个方法。 length是可选填写的参数,它是指定在返回的字符串中包括的字符个数,不可为负数。

以下是代码示例及输出结果:

var str = 'JavaScript';
var newStr = str.substr(4);
console.log(newStr); // 输出 Script
newStr = str.substr(4,3);
console.log(newStr); // 输出 Scr

介绍了三种使用JavaScript截取指定位置的字符串的方法,大家可以根据实际需求,自由使用。