1.String
String是对应字符串的引用类型。要创建一个String对象,使用String构造函数并传入一个数值。
let stringObj = new String("Hello World!")
String对象的方法可以在所有字符串原始值上调用。每个String对象都有length属性,表示字符串中字符的数量。
let str = 'hello world';
console.log(str.length); //11
charAt()方法返回给定索引位置的字符。
let str = 'abcde';
console.log(str.charAt(2)) // 'c'
2.字符串操作方法
2-1.连接字符串
(1)使用运算符 +,当+的操作目标包含字符串时,还能将其他类型强制类型转换为字符串类型。
let str1 = 'hello';
let str = str1 + ' world';
console.log(str) //'hello world'
let num = 123;
let strr = 'blue';
console.log(num + strr); //123blue
let bool = true;
let strr = 'blue';
console.log(num + strr); //trueblue
(2)使用concat()方法。(不会修改源字符串)
let str1 = "hello";
let result = str1.concat(' world');
console.log(result) // "hello world"
console.log(sre1) //hello
let str = str1.concat(' world','!');
console.log(str) // 'hello wo'
2-2.提取子字符串
JS提供了3个方法:slice()、substr()、substring()。都接收1或2个参数。他们也不会修改源字符串。
(1)slice()第一个参数表示子字符串开始的位置,第二个表示子字符串结束的位置(即在该位置之前的字符会被提取,左闭右开)
let str = 'hello world!'
console.log(str.slice(3)); //lo world!
console.log(str.slice(3, 7)); //lo w
当参数是负数的时候,slice()将所有负值参数都当成字符串长度加上负参数。
let str = 'hello world!'
console.log(str.slice(-3)); //ld!
console.log(str.slice(3, -4)); //lo wo
长度为12,参数-3表示12-3=9,str.slice(-3) 等价于 str.slice(9);-4表示12-4=8,slice(3,-4)等价于slice(3,8)。但是我们可以把负数记成从结尾开始,即-1就是最后一位,-2就是倒数第二位...
(2)substring()第一个参数表示子字符串开始的位置,第二个表示子字符串结束的位置(即在该位置之前的字符会被提取,左闭右开)
let str = 'hello world!'
console.log(str.substring(3)); //lo world!
console.log(str.substring(3, 7)); //lo w
当参数是负数的时候,substring()将所有负参数都转换为0.
let str = 'hello world!'
console.log(str.substring(-3)); //hello world!
console.log(str.substring(3, -4)); //hel
substring(-3)等价于substring(0),返回整个字符串;substring(3,-4)等价于substring(3,0)等价于substring(0,3)(会将小的参数作为起点,大的参数作为终点,如果是slice()会返回空字符串)
let str = 'hello world!'
let a = str.slice(3, 2);
console.log(typeof a); //string
console.log(a.length); //0
(3)substr()第一个参数表示子字符串开始的位置,第二个表示要返回的子字符串数量(省略第二个参数提取到末尾)
let str = 'hello world!'
console.log(str.substr(3)); //lo world!
console.log(str.substr(3, 2)); //lo
当参数为负数时,substr()会将第一个负参数当成字符串长度加上该值,将第二个负参数转换为0
let str = 'hello world!'
console.log(str.substr(-3)); //ld!
console.log(str.substr(-3, 2)); //lo
console.log(str.substr(3, -2)); //
substr(-3)等价于substr(str.length-3),substr(9);substr(3,-2)等价于substr(3,0)返回空字符串
2-3.查找是否包含子字符串
(1)indexOf()查找字符串。如果找到就返回该字符串的索引位置,没有找到就返回-1.
let str = 'hello world!'
console.log(str.indexOf('llo')); //2
console.log(str.indexOf('lk')); //-1
console.log(str.indexOf('l')); //2
indexOf()还可以接收第二个参数,表示要从哪里开始查找。
let str = 'hello world!'
console.log(str.indexOf('l', 3)); //3
(2)lastIndexOf()和indexOf的使用方法一模一样,唯一的区别就是indexOf是从字符串开头开始到末尾查找,lastIndexOf()是从字符串末尾到开头开始查找。
let str = 'hello world!'
console.log(str.lastIndexOf('llo')); //2
console.log(str.lastIndexOf('lk')); //-1
console.log(str.lastIndexOf('l')); //9
console.log(str.lastIndexOf('l', 5)); //3
但是该方法找到字符串后就会停止查找,所以只会返回最开始查找到的索引。如果我们想查找所有的该怎么办呢?
let str = 'Lorem ipsum dolor sit amet, consecterur adipisicing elit';
let positions = [];
let pos = str.indexOf('e');
while (pos > -1) {
positions.push(pos);
pos = str.indexOf('e', pos + 1);
}
console.log(positions); //[ 3, 24, 32, 35, 52 ]
此外,ES6新增了includes()方法,用于查找字符串,并返回一个布尔值。
let str = 'foobarbaz';
console.log(str.includes('bar')); //true
console.log(str.includes('qux')); //false
而且includes也可以接收第二个参数,表示开始查找的起始位置。
let str = 'foobarbaz';
console.log(str.includes('bar')); //true
console.log(str.includes('bar', 4)); //false
console.log(str.includes('foo')); //true
console.log(str.includes('foo', 1)); //false
此外,ES6还新增了startsWith()和endsWith()方法。startsWidth()表示以某字符串开头,endsWith()表示以某字符串结尾。
let str = 'foobarbaz';
console.log(str.startsWith('bar')); //false
console.log(str.startsWith('foo')); //true
console.log(str.endsWith('bar')); //false
console.log(str.endsWith('baz')); //true
startsWith()和endsWith()也可以接收第二个参数,表示是否以第二个参数位置的字符串为开始或结尾。
let str = 'foobarbaz';
console.log(str.startsWith('bar')); //false
console.log(str.startsWith('bar',3)); //true
console.log(str.endsWith('bar')); //false
console.log(str.endsWith('bar', 6)); //true
2-4.字符串的其他方法
(1)trim()。会创建字符串的一个副本,删除前、后所有的空格符,再返回结果。
let str = ' hello world ';
let newStr = str.trim();
console.log(newStr); //'hello world'
console.log(str);//' hello world '
不改变源字符串
(2)repeat()。接收一个参数,表示该字符串要复制几次,然后返回新的字符串。
let str = 'a';
console.log(str.repeat(5)); //'aaaaa'
(3)padStart()和padEnd()。用于复制字符串,如果小于指定长度,在相应一边填充字符。有两个参数,第一个参数是长度,第二个参数是可选的填充字符串,默认是空格。
let str = 'foo';
console.log(str.padStart(6)); //' foo'
console.log(str.padStart(9, 'a')); //'aaaaaafoo'
console.log(str.padEnd(6)); //'foo '
console.log(str.padEnd(9, 'a')); //'fooaaaaaa'
console.log(str.padStart(8, 'bar')); //'barbafoo'
console.log(str.padStart(2,'a')); //'foo'
console.log(str.padEnd(8, 'bar')); //'foobarba'
console.log(str.padEnd(2,'a')); //'foo'
如果第一个参数小于或等于字符串长度,则返回原字符串。
(4)toLowerCase()和toUpperCase()。用于字符串的大小写转换。
let str = 'hello world';
let STR = 'HELLO WORLD';
console.log(str.toUpperCase()); //HELLO WORLD
console.log(str.toLowerCase()); //hello world
(5)localCompare()方法。接收一个参数,用于比较两个字符串,如果按照字母表顺序,字符串应该排在字符串参数前面,返回负值(-1);如果字符串等于字符串参数,返回0;如果按照字母表顺序,字符串应该排在字符串参数后面,返回正值(1)。(按照国际化字符表进行比较的)
let color = 'yellow';
console.log(color.localeCompare('yelloa')); //1
console.log(color.localeCompare('yellow')); //0
console.log(color.localeCompare('zoo')); //-1
该方法一般单独使用较少,都是配合sort()函数进行排序。
let strList = ['cc', 'ee', 'ca', 'aa'];
strList.sort((a, b) => {
return a.localeCompare(b);
});
console.log(strList); //["aa", "ca", "cc", "ee"]
此外localCompare()可以用于比较中文汉字,可以对中文按照拼音进行排序。
console.log('一二三四五六七八九十'.split('').sort((a, b) => a.localeCompare(b, 'zh-CN')).join(''));
//八二九六七三十四五一
//拼音 ba er jiu liu qi san shi si wu yi
console.log('一'.localeCompare('咦', 'zh')); //-1
localCompare是根据我们的中文系统,把汉字先转换成了拼音,再进行了比较;对于同拼音的汉字,js再根据声调进行比较。 多音字是比较麻烦的,localeCompare无法正确比较多音字,例如凹,可以读作ao或者wa,wa是少数读音,ao是多数读音,比较的时候只能比较出作为ao的读音,无法比较出wa的读音,例如:
console.log('啊'.localeCompare('凹', 'zh-CN')); //-1,啊在凹前面
console.log('吧'.localeCompare('凹', 'zh-CN')); // 1,吧在凹后面
2.5字符串的模式匹配
(1)match()方法。接收一个参数,可以是正则表达式字符串或者RegExp对象,找到返回一个数组,没有找到返回null。
let text = 'cat, bat, sat, fat';
let pattern = /.at/g;
let result = text.match(pattern);
console.log(result); //[ 'cat', 'bat', 'sat', 'fat' ]
console.log(text.match(/r/)); //null
/.at/g 表示查找一个长度为3的,不以换行为开头的以at结尾的字符串,g表示全局查找。有关正则表达式,我们下一节再仔细探讨。
(2)search()方法。接受一个参数,参数也是正则表达式字符串或者RegExp对象。但是它返回的是第一个匹配的位置索引。(类似indexOf())
let text = 'cat, bat, sat, fat';
let pattern = /at/;
console.log(text.search(pattern)); //1
(3)replace()方法。接收两个参数,第一个参数可以是RegExp对象或者字符串,第二个参数是一个字符串或者函数,函数应该返回一个字符串,用于把匹配项替换。如果第一个参数是字符串,则只会替换第一个子字符串。
let text = 'cat, bat, sat, fat';
console.log(text.replace('at', '1')); //c1, bat, sat, fat
console.log(text.replace(/at/g, '1')); //c1, b1, s1, f1
console.log(text.replace(/at/g, item => '')); //c, b, s, f