JS之字符串方法
这主要是JS中对字符串的一些方法函数,废话不多说!上干货!!
charAt()charCodeAt()concat()slice()substr()substring()indexOf()lastIndexOf()trim()toLowerCase()toUpperCase()split()
var str = 'hello world';
console.log(str.charAt(2));
charCodeAt()获取字符串当前索引值对应的ASCⅡ码
var str = 'hello world';
console.log(str.charCodeAt(2));//获取字符的ASCⅡ码
var str = 'hello world';
console.log(str.concat(' hetao'))
//通常不使用 一般都用 + 来做多个字符的拼接
slice() substr() substring()
字符串剪切
var str = 'hello world';
console.log(str.slice(2));
console.log(str.substr(2));
console.log(str.substring(2));
console.log(str.slice(2,4));
console.log(str.substr(2,4));
console.log(str.substring(2,4));
可以看到三个函数基本一样 不一样的是 substr()
当我们给函数设定区间的时候slice subtring 设定的是开始和结束的位置,而substr 第二个参数是返回的个数
indexOf() lastIndexOf() 查找对应字符位置
var str = 'hello world';
console.log(str.indexOf('o'));//从前往后
console.log(str.lastIndexOf('o'));//从后往前
console.log(str.indexOf('o',5));//第二值是设定查找的位置
console.log(str.lastIndexOf('o',5));//第二值是设定查找的位置
var str = ' hello world ';
console.log(str.trim());//
toLowerCase() 大转小 toUpperCase() 小转大
var str = 'HETAO';
console.log(str.toLowerCase());
console.log(str.toUpperCase());
查找当前字符传中的所有位置
var str = "If I can see it, then I can do it. If I just believe it, there's nothing to it";
var arr = []
var position = str.indexOf('i');
while(position > -1){ // 逻辑就是 当我们查到 字符串结束没有查到的时候就会返回-1
arr.push(position);
position = str.indexOf('i',position + 1);
}
console.log(arr);
split 将字符串拆分成子字符串并存放到数组中
var url = 'user=hetao&pwd=123456';
var item = url.split('&');
console.log(item);