概述
substring() 返回字符串两个索引之间(或到字符串末尾)的字串。
语法
str.substring(indexA[, indexB])
参数
-
indexA - 一个 0 到字符串长度之间的整数。
-
indexB - (optional) 一个 0 到字符串长度之间的整数。
描述
substring 提取从 indexA 到 indexB(不包括)之间的字符。特别地:
- 如果
indexA等于indexB,substring返回一个空字符串。 - 如果省略
indexB,substring提取字符一直到字符串末尾。 - 如果任一参数小于 0 或为
NaN,则被当作 0。 - 如果任一参数大于
stringName.length,则被当作stringName.length。
如果 indexA 大于 indexB,则 substring 的执行效果就像两个参数调换了一样。例如,str.substring(1, 0) == str.substring(0, 1)。
示例
例子:使用 substring
下例使用 substring 输出字符串 "Mozilla" 中的字符:
// 假设 print 函数已被定义 var anyString = "Mozilla"; // 输出 "Moz" console.log(anyString.substring(0,3)); console.log(anyString.substring(3,0)); // 输出 "lla" console.log(anyString.substring(4,7)); console.log(anyString.substring(7,4)); // 输出 "Mozill" console.log(anyString.substring(0,6)); // 输出 "Mozilla" console.log(anyString.substring(0,7)); console.log(anyString.substring(0,10));
例子:替换一个字符串的子字符串
下例替换了一个字符串中的子字符串。可以替换单个字符和子字符串。该例结尾调用的函数将 "Brave New World" 变成了 "Brave New Web"。
function replaceString(oldS, newS, fullS) {
// Replaces oldS with newS in the string fullS
for (var i = 0; i < fullS.length; i++) {
if (fullS.substring(i, i + oldS.length) == oldS) {
fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
}
}
return fullS;
}
replaceString("World", "Web", "Brave New World");
需要注意的是,如果 oldS 是 newS 的子字符串将会导致死循环。例如,尝试把 "World" 替换成 "OtherWorld"。一个更好的方法如下:
function replaceString(oldS, newS,fullS){
return fullS.split(oldS).join(newS);
}
上面的代码只是子字符串操作的一个例子。如果你需要替换子字符串,更多时候会用到 String.prototype.replace()。
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition. | Standard | Implemented in JavaScript 1.0 |
| ECMAScript 5.1 (ECMA-262) String.prototype.substring |
Standard | |
| ECMAScript 6 (ECMA-262) String.prototype.substring |
Draft |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |