常用API
检索
-
index of()
检索子串首次出现的下标,没有该子串则返回-1
①indexof(substr)
var str ="In order to be irreplaceable one must always be different";
var substr="order";
var id = str.indexOf(substr);
console.log(id);//输出3
②indexof(substr,15)
从15号位开始检索be首次出现的下标
console.log(str.indexOf("be",15));//输出45
-
lastIndexOf()
检索子串最后一次出现的下标
str ="In order to be irreplaceable one must always be different";
var strId = str.indexOf("be");
console.log(strId);//输出12
console.log(str.indexOf("be",strId + 1));//输出45
console.log(str.lastIndexOf("be"));//输出45
-
includes()
检索子串是否存在(区分大小写)
var str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false
替换
-
replace(str1,str2)
把字符串中值中找到的第一个str1替换为str2,不会改变调用它的字符串值,返回一个被替换后的新字符串
var str = "To be, or not to be, that is the question.";
console.log(str.replace("be","is")) ;
//In order to is irreplaceable one must always be different
console.log(
str.replace(
"dog",
/*
将sub重复10次
sub为找到的第一个子串
返回一个新的子串 替换sub
*/
function (sub) {
console.log("sub=", sub);
let newSub = "";
for (var i = 0; i < 10; i++) {
newSub += sub;
}
return newSub;
}
)
);
-
replaceAll()
把字符串中值中找到的
全部str1替换为str2,不会改变调用它的字符串值,返回一个被替换后的新字符串
//将所有的脏话替换为*
var str ="你烧饼你就是大烧饼";
var word = "烧饼";
function shield(str,word){
return str.replaceAll(word,"**");
}
console.log(shield(str,word));//输出你是**你就是大**
截取
-
substring(start,end) (包括start,不包括end)
返回索引start和索引end之间的部分
-
substring(start)
返回索引start到字符串的末尾之间的部分
-
split()
将字符串划分为子串数组,返回该数组
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"
-
slice( begin, end)
提取字符串的一部分并将其作为新字符串返回,而不修改原始字符串
注:begin值为负数则从字符串后面开始数,省略end则一直提取到字符串末位
slice( begin)
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// expected output: "the lazy dog."
-
trim()
返回一个将str开头和结尾的空格都去掉的字符串
判断
判断str是否以指定子串开头或结尾,是则返回true,否则返回false
-
startsWith()
-
endsWith()