根据《JavaScript高级程序设计》,整理string用法

1,charAt&charCodeAt

这两个方法都接收一个参数,即基于0的字符串位置。其中,charAt方法以单字符字符串的形式返回给定位置的那个字符。


var stringValue = "hello world";
console.log(stringValue.charAt(4));	//"o"

charCodeAt方法返回字符的字符编码


var stringValue = "hello world";
console.log(stringValue.charCodeAt(4));	//111


2,concat

concat方法用于将一或多个字符串拼接起来。


//没啥卵用,直接用+拼接就好


3,slice&substr&substring

三个方法都接收一或两个参数,第一个指定字符串的开始位置,第二个(如果有的话)表示字符串到哪里结束。

slice和substring的第二个参数指定的是字符串最后一个字符串后面的位置,而substr的第二个参数指定的则是返回的字符个数。如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。

(注:这三个方法都不会修改原始字符串。)

在没有负值的情况下,slice和substring的表现一致。


var stringValue = "hello world";
console.log(stringValue.slice(1,3));	//el
console.log(stringValue.substring(1,3));	//el
console.log(stringValue.substr(1,3));	//ell

在对于负值,三者处理都不相同,这里要提下slice的负值。如果slice的第二个参数为负值,此负值会加上字符串长度变成一个新数字。利用这个特性,

我们可以用


slice(0,-1);

非常简单的截掉字符串的最后一个字符,不需要再使用


slice(0,str.length-1)

这种臃肿的方式来实现





4,indexOf&lastIndexOf

indexOf方法从字符串的开头向后搜索字符串,而lastIndexOf方法时从字符串的末尾向前搜索字符串,找不到一样返回-1。第二个参数表示从字符串哪个位置开始搜索。

var stringValue = "hello world";
console.log(stringValue.indexOf("o"));	//4
console.log(stringValue.lastIndexOf("o"));	//7
console.log(stringValue.indexOf("o",2));	//4


5,trim

trim方法会创建一个字符串的副本,删除前置及后缀的所有空格,然后返回结果。

var stringValue = "     hello world     ";
console.log(stringValue.trim());	//"hello world"


6,toLowerCase&toUpperCase

大小写转换

var stringValue = "hello world";
console.log(stringValue.toUpperCase());	//"HELLO WORLD"
var stringValue = "HELLO WORLD";
console.log(stringValue.toLowerCase());	//"hello world"


7,exec&match将会在另一篇单讲正则的博客中提及

8,localeCompare

//比较两个字符串的排序,没什么卵用,不说了


9,fromCharCode

fromCharCode方法是String构造函数的静态方法,这个方法接收一或多个字符编码,然后将他们转换成一个字符串。这是与charCodeAt的反向操作。


console.log(String.fromCharCode(104,101,108,108,111));	//"hello"

10,split

split() 方法用于把一个字符串分割成字符串数组。

参数可以是字符串或正则表达式

如果传入"",可以将字符串的每个值分割成数组