字符串方法

1.字符串截取 substring()

//包含开始   不包含结束  (返回新字符串,不改变原字符串)

let str = "123456";

console.log( str .substring(1,3) );  //23

console.log( str .substring(1, 100) ); //"23456"

console.log( str .substring(1) );  //"23456"

console.log(str );  //"123456"

2. 转大小写 

 let str = "ABCdef";

 console.log( str.toLocaleUpperCase() );  //ABCDEF

console.log( str.toLocaleLowerCase() ); //abcdef console.log( str ); //ABCdef

3.字符串转数组 split()

 let date = "2018-07-08";

 console.log( date.split("-") ); //['2018', '07', '08']

 let nums = "1,2,3,4,5"; 

 console.log(nums.split(","));  //['1', '2', '3', '4', '5']

 let str = "阿司法鉴定所";

 console.log( str.split("") );  // ['阿', '司', '法', '鉴', '定', '所']

3.查找字符串 indexOf()

let str = "1234567";

/*返回参数字符串最早出现在afei中的位置*/

console.log(   str.indexOf("2")  ); // 1

console.log(   str.indexOf("0")  ); // -1

 console.log(   str.indexOf("4")  ); //3

4.字符串截取  slice(start,end)

截取字符串,start指定字符串开始的位置,end不在截取范围之内    前包后不包

 let str = "12345678";

 console.log( str.slice(2, 6) );  //3456   

5.字符串替换 replace()

let  str = '#home#home'

let str1= 'home'

let newStr = str.replace(str1, 'home1') 

//得到newStr1的结果为"#home1#home"

6.字符串去重

let str = '123123455'

new Set(str)    //   {'1', '2', '3', '4', '5'}    //去重转化成类数组

[...new Set(str)]   //['1', '2', '3', '4', '5']    //转成数组

[...new Set(str)].join('')   '12345'       //拼接字符串

        

 

posted @ 2022-04-13 19:17  小成-  阅读(49)  评论(0)    收藏  举报