一、基本数据类型
在JavaScript中:String、Number、Boolean、Null、Undefined、Symbol(ES6新增)属于基本数据类型。
基本类型是不可以通过方法改变自身的值的,所以String变量调用自身的方法后,原来的值并未改变,而是返回改变后产生的新值。
二、常用方法
1、charAt(索引值)
查找字符串具体位置(下标)的字符值
"yancy".charAt(2) // n
charCodeAt(index): 返回指定位置字符Unicode编码。
String.fromCharCode(Unicode) 方法返回使用指定的Unicode值序列创建的字符串。
2、indexOf(searchValue[,fromIndex])
返回searchValue
第一次出现的索引位置,找不到时返回-1。
可以指定从fromIndex
开始查找。
"yancy".indexOf("y") // 0
lastIndexOf与indexOf用法一样,但是会从字符串末尾从前往后查找。
"yancy".lastIndexOf("y") //4
3、search(regexp)
返回匹配(正则表达式regexp)的位置,找不到返回-1。
4、match(regexp)
返回匹配到的字符,以数组形式返回;找不到返回null。
5、replace(regexp|substr,newSubstr)
找到字符串(参数1)并替换成相应字符串(参数2)。
"Hi , how are you? Hi , I'm fine.".replace("Hi","Hello")
//Hello , how are you? Hi , I'm fine.
可以看到,只替换了第一个匹配的字符串。
replaceAll会替换所有匹配的子字符串。
"Hi , how are you? Hi , I'm fine.".replaceAll("Hi","Hello")
//Hello , how are you? Hello , I'm fine.
6、substring(indexA,indexB)
字符串截取准确的字符,indexA首位置(包含),indexB末尾位置(不包含)
"yancy zhang".substring(0,5)
//yancy
当参数只有indexA时,从indexA开始截取之后的所有子字符串。
"yancy zhang".substring(6)
//zhang
7、slice(beginSlice,endSlice)
字符串截取,首末位置,与substring用法一样,然后不同的是可以传入负值(负值是从末尾数负数,字符串末尾下标从-1开始,向前递减)
"yancy zhang".slice(-6,-1)
//zhan
8、substr(index,length)
返回匹配的字符串,从index开始,获取length长度的字符串。未指定length则一直取完。与substring和slice区分:
substr第二个参数为length,是要截取的字符串长度。而前二者是要截取的末尾下标。
"yancy zhang".substr(0,5)
//yancy
"yancy zhang".substr(6)
//zhang
9、slipt(separator[,limit])
分隔符函数,以数组方式返回分隔后的字符串。注意:返回一个字符串数组。
会找到字符串中的separator(分隔符),然后以此为依据将字符串分成子字符串并存入数组
中。
"one-two-three".split("-")
//['one', 'two', 'three']
第二个参数limit限制了返回数组长度。
"one-two-three".split("-",2)
//['one', 'two']
10、toLowerCase()/toUpperCase()
将所有的字符串都转换为小/大写字母。
"yancy".toUpperCase()
//YANCY
将首字母转为大写:
let name = "yancy";
name = name[0].toUpperCase() + name.slice(1);
// Yancy