1、字符串的方法
1-1 增加
1-1-1 concat 拼接
var a = 'hello'
var b = "world"
console.log(a.concat(b));
1-2 查询
1-2-1 slice(startIndex,endIndex)
1-2-2 substr(index,length)
1-2-3 substring(startIndex,endIndex)
var arr = "hello"
console.log(arr.slice(0)); // hello
console.log(arr.slice(0,3)); // hel
console.log(arr.substr(0,3)); // hel
console.log(arr.substring(0,2)); // he
1-2-4 charAt(index) 根据下标查找对应的值
var str = "hello"
console.log(str.charAt(1)); // e
1-2-5 indexOf(value) 根据值查找对应的下标
var arr = "hello";
console.log(arr.indexOf('e')); // 1
1-2-6 includes 是否包含某位(多位)字符
var arr = "hello"
console.log(arr.includes("eh")); //false
1-3 length 字符串的长度
var str = "hello"
console.log(str.length);
var s = "故事的结尾,心上人"
console.log(handleStr(s));
function handleStr(value){
if(value.length>5){
return value.slice(0,5)+"..."
}
return value
}
1-4 其他方法
1-4-1 split(sperate)
把一个字符串分割成字符串数组
var str = "hello";
console.log(str.split());//["hello"]
*console.log(str.split(""));//["h" "e" "l" "l" "o"] 以""来分割
console.log(str.split("e"));//["h" "llo"]
//"hello"取反输出
var str = "hello";
var arr = str.split("");//字符串数组
arr.reverse();
var s = arr.join("");//字符串
console.log(s);//olleh
var arr = [1,2,3,4,5,6,7,8,9];
var sum = [];
//slice(startIndex,startIndex+3)
for(var i=0; i<arr.length; i+=3){
var res = arr.slice(i,i+3);
// console.log(res);
sum.push(res);
}
console.log(sum); //[[1,2,3],[4,5,6],[7,8,9]]
1-4-2 search()
search 返回值的下标,没有返回-1,和indexOf类似
var str = "ywuie";
var index = str.search("i");//3
console.log(index);
console.log(str.indexOf("i"));//3
1-4-3 match()
match返回匹配的字符,返回一个数组
var str = "hello";
var arr = str.match("l");
console.log(arr);//["l", index: 2, input: "hello", groups: undefined]
1-4-4 replace()
replace()可以替换字符
var str = "hello";
console.log(str.replace("l",""));//helo
1-4-5 trim() 去除字符串前后的空格
// 正则表达式: /^\s+|\s+$/g
var str = " hello ";
var arr = []
arr.push(str.trim())
console.log(arr)
// 正则表达式: /^\s+|\s+$/g
var str = " hello ";
var arr = []
arr.push(str.trim())
console.log(arr)