简单数据类型没有属性和方法,只有值。但是有的时候发现简单数据类型也可以使用属性和方法?
这是因为,在简单数据类型获取复杂数据类型属性和方法时,js为了方便会将简单数据类型包装成复杂数据类型,获取值,在得到值之后,最终会变为简单数据类型。
简单数据类型:Number , String, Boolean, null, undefined
基本包装类型: Number , Boolean , String
今天介绍一下简单数据类型string的一些用法,一定要和数组的方法区分开,两者不可混用
1.字符串可以和数组一样,进行遍历,但是字符串不是数组,方法不可以混用
var str="abcde";
for(var i =0;i<str.length;i++){
console.log(str[i]);
}
2.indexOf和lastIndexOf 查找值在字符串中第一次和最后一次出现的下标,没有找到,返回-1
3.trim() 去除字符串首尾的空格
4.转大小写
toUpperCase 转大写
toLowerCase 转小写
5.对字符串进行拼接,返回新的字符串 concat
var str1 = 'hello';
var str2 = 'world!';
var newStr = str1.concat(str2);
6.字符串截取
slice(begin,end) : 从begin(下标)开始截取,截取到end结束,包括begin,不包括end
subString(begin,end): 从begin(下标)开始截取,截取到end结束,包括begin,不包括end
subStr(begin,length); 从begin开始截取,截取length个
7.split 将字符串拆分成数组,可以指定以什么为分割符拆分,会返回一个拆分得到的数组
var str ="a|b|c|d";
var arr = str.split('|'); //['a','b','c','d'];
var str2 = "abcd";
var arr2 = str.split(); //['abcd'];
在这里补充一下数组的join方法,它是将数组的值拼接成字符串,返回拼接成的新字符串,不过join是默认以,为分割
var str3 = arr2.join();//a,b,c,d
8.replace('a','b') 将字符串中第一个a转换为b,返回替换后的结果
如果需要实现全部替换,那可以用正则实现