JS中常用的字符串方法

192 阅读2分钟

字符方法:

1. charAt

返回子字符串,index为字符串下标,index取值范围[0,str.length-1]

   //示例
   var str="hello world";
   console.log(str.charAt(1));//e 

  //charAt方法是以单字符字符串的形式返回给定位置的那个字符 

2. str.charCodeAt(index)

返回子字符串的unicode编码,index取值范围同上

 //示例
 var str="hello world"; 
 console.log(str.charCodeAt(1));//101 

 //charCodeAt方法获取到的不是字符而是字符编码 

字符串操作方法:

1.concat()

拼接字符串的,可以接受多个参数,实践中最多还是用 '+',操作方便。

 //示例
 var yhl = "hello "
 var yhl1 = yhl.concat("world")
 var yhl2 = yhl.concat("world" ,"!")
 console.log(yhl); //hello 
 console.log(yhl1); //hello world
 console.log(yhl2); //hello world!

截取字符串

1.slice()

str.slice(start,end);  两个参数可正可负,负值代表从右截取,返回值:[start,end) 也就是说返回从start到end-1的字符

 //示例
 //slice()第一个参数指定子字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置 
 var yhl="hello world"; 
 console.log(yhl.slice(3));//lo world 
 console.log(yhl.slice(3,7));//lo w  7表示子字符串最后一个字符后面的位置  
            //简单理解就是包含头不包含尾 空格也算
console.log(yhl.slice(3,-4));//lo w  负值代表从右截取 

2.substring()

两个参数都为正数,返回值:[start,end) 也就是说返回从start到end-1的字符

//示例
//第一个参数指定子字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置 
var yhl="hello world"; 
console.log(yhl.substring(3));//lo world 
console.log(yhl.substring(3,7));//lo w 
console.log(yhl.substring(3,-4));//hel  会转换为console.log(yhl.substring(3,0)); 

字符串位置方法

1. indexOf(searchString,startIndex)

返回子字符串第一次出现的位置,从startIndex开始查找,找不到时返回-1

//示例
var yhl="hello world"; 
console.log(yhl.indexOf("o"));//4 
console.log(yhl.indexOf("o",6));//7 

2. lastIndexOf(searchString,startIndex)

从由往左找子字符串,找不到时返回-1

//示例
 var yhl="hello world"; 
 console.log yhl.lastIndexOf("o"));//7 
 console.log(yhl.lastIndexOf("o",6));//4 

删除字符串空格

1. trim()

用来删除字符串前后的空格

//示例
 var yhl="   hello world   "; 
 console.log('('+yhl.trim()+')');//(hello world) 
 console.log('('+yhl+')');//(   hello world   ) 

字符串大小写转换方法

1.toLowerCase()

把字符串的全部小写转换方式

//示例
 var yhl="hello world"; 
 var yhl1 = "HELLO WORLD"
 console.log(yhl.toLowerCase());  // hello world
 console.log(yhl1.toLowerCase()); // hello world

2.toUpperCase()

把字符串的全部大写转换方式

//示例
 var yhl="hello world"; 
 var yhl1 = "HELLO WORLD"
 console.log(yhl.toUpperCase()); // HELLO WORLD
 console.log(yhl1.toUpperCase()); // HELLO WORLD

字符串分割成数组

split(separator,limit)

参数1指定字符串或正则,参照2指定数组的最大长度

//示例
var yhl="red,blue,green,yellow"; 
console.log(yhl.split(","));//["red", "blue", "green", "yellow"] 
console.log(yhl.split(",",2));//["red", "blue"]  第二个参数用来限制数组大小