操作字符串常用方法:
// concat 将两个或多个字符串组合起来形成新的字符串
const [ str, feeling] = ['Anyway, the feelings are now' ,' Not?'];
const name = str.concat(feeling);
name => // 'Anyway, the feelings are now Not?'
// indexOf 返回字符串中第一次出现的索引值,如果没有就返回 -1;
const str='the feelings are now';
str.indexOf('e') => 2;
str.indexOf('t') => -1;
// charAt 返回指定位置的字符串
const str='the feeling are new';
str.charAt(2) => e
str.charAt(100) =>''; //如果参数大于字符串长度,结果返回空值;
// lastIndexOf 返回字符串从后往前第一次出现的索引值, 没有返回 -1;
str.lastIndexOf('e') => 17
// substring 返回字符串里面一串子字符串,里面有两个参数,
const str='the feeling are new';
// 1. 当只有一个参数时,截取从参数开始的位子到字符串末尾。
str.subString(5) => eeling are new
// 2.当只有两个参数时,截取从一个参数到另一个参数之间的字符串。
str.subString(5,10) => eelin
// 3. 当参数大于字符串的长度时,返回空
str.subString(100) => ''
// 4. 当有两个参数时,第一个参数大于第二个参数时,截取是以小的为开头,大的为结尾。
str.subString(10,5) => eelin
// 5.当有两个参数时,里面有一个参数大于字符串长度时,则以小的准,截取到字符串末尾
str.subString(10,100) => g are new
// substr 返回字符串里的子字符串 第一个参数是索引,第二个是截取长度
str.substr(2,4) => 'e fe';
当索引大于字符串长度返回为空,当截取长度大于字符串长度时,以索引值到字符串最后为准。
str.substr(100,2) => '' ; str.substr(2,100) => 'e feeling are new';
// slice 返回字符串里的子字符串 两个参数都是索引值和substring一样,但是也不一样
const str='the feeling are new';
// slice的两个参数可为负数, 当地一个参数为负数时,表示从末尾开始截取,此时第二个参数必须为负数
// 且第二个参数要大于第一个参数,同为负数的情况下。否则返回的字符串为空
// 当第一个参数为正数,第二个参数为负数时,表示截取的是从正下标到倒数下标的距离
eg: str.slice(2,5) => 'e f';
str.slice(-2,-5) => ''; str.slice(-5,-2) => 'e ne'; str.slice(5,-2) => 'eeling are n';
// split 将字符串通过分隔符转换成数组
str.split(' ') => ['the' ,'feeling' ,'are' ,'new'];