String类型
String类型是字符串的对象包装类型。可以使用String构造函数来创建:
var stringObject = new String("hello world");
String对象的方法也可以在所有基本的字符串值中访问到的。其中,继承的valueOf()、toLocaleString()和toString()方法,都返回对象所表示的基本字符串值。
String类型的每个实例都有一个length属性,表示字符串中包含多少个字符。
var stringValue = "hello world";
alert(stringValue.length); //"11"
注意:即使字符串中包含双字节字符(不是占一个字节的ASCII字符),每个字符也仍然算一个字符。
String类型提供了很多方法,用于辅助完成对ECMAScript中字符串的解析和操作。
1.字符方法
两个用于访问字符串中特定字符的方法是:charAt()和charCodeAt()。这两个方法都接收一个参数,即基于0的字符位置。其中,charAt()方法以单字符字符串的形式返回给定位置的那个字符。
var stringValue = "hello world";
alert(stringValue.charAt(1)); //"e"
charCodeAt()方法返回字符编码:
var stringValue = "hello world";
alert(stringValue.charCodeAt(1)); //输出"101"("e"的字符编码)
ECMAScript5中还定义了另一个访问个别字符的方法。在支持此方法的浏览器中,可以使用方括号加数字索引来访问字符串中的特定字符。
var stringValue = "hello world";
alert(stringValue[1]); //"e"
2.字符串操作方法
(1)**concat()**方法,用于将一或多个字符串拼接起来,返回拼接得到的新字符串。
var stringValue = "hello ";
var result = stringValue.concat("world");
alert(result); //"hello world"
alert(stringValue); //"hello "
也可以接收任意多个参数,也就是可以通过它拼接任意多个字符串。
var stringValue = "hello ";
var result = stringValue.concat("world", "!");
alert(result); //"hello world!"
alert(stringValue); //"hello "
虽然concat()方法是专门用来拼接字符串的方法,但实践中使用更多的还是加号操作符(+)。而且,使用加号操作符在大多数情况下都比使用concat()方法简单易行(特别是在拼接多个字符串的情况下)。
ECMAScript还提供了3个基于字符串创建新字符串的方法:slice()、substr()和substring()。
slice()方法接收一或两个参数,返回被操作字符串的一个子字符串。第一个参数指定子字符串的开始位置,第二个参数(在指定的情况下)表示字符串到哪里结束(子字符串最后一个字符后面的位置)。如果没有传递第二个参数,则将字符串的长度作为结束的位置。在传递的参数是负值的情况下,slice()方法会将传入的负值与字符串的长度相加。
substr()方法接收一或两个参数,返回被操作字符串的一个子字符串。第一个参数指定子字符串的开始位置,第二个参数指定的则是返回的字符个数。如果没有传递第二个参数,则将字符串的长度作为结束的位置。在传递的参数是负值的情况下,substr()方法将负的第一个参数加上字符串的长度,而将负的第二个参数转换为0。
substring()方法接收一或两个参数,返回被操作字符串的一个子字符串。第一个参数指定子字符串的开始位置,第二个参数(在指定的情况下)表示字符串到哪里结束(子字符串最后一个字符后面的位置)。如果没有传递第二个参数,则将字符串的长度作为结束的位置。在传递的参数是负值的情况下,substring()方法把所有负值参数都转换为0。
slice()、substr()和substring()方法不会修改字符串本身的值–只是返回一个基本类型的字符串值,对原始字符串没有任何影响。
var stringValue = "hello world";
alert(stringValue.slice(3)); //"lo world"
alert(stringValue.substring(3)); //"lo world"
alert(stringValue.substr(3)); //"lo world"
alert(stringValue.slice(3, 7)); //"lo w"
alert(stringValue.substring(3, 7)); //"lo w"
alert(stringValue.substr(3, 7)); //"lo worl"
var stringValue = "hello world";
alert(stringValue.slice(-3)); //"rld"
alert(stringValue.substring(-3)); //"hello world"
alert(stringValue.substr(-3)); //"rld"
alert(stringValue.slice(3, -4)); //"lo w"
alert(stringValue.substring(3, -4)); //"hel"
alert(stringValue.substr(3, -4)); //""(空字符串)
注:substring()方法会将较小的数作为开始位置,将较大的数作为结束位置。上例substring(3, -4)相当于调用了substring(0, 3)。
3.字符串位置方法
从字符串中查找子字符串的方法:**indexOf()和lastIndexOf()**方法。这两个方法都是从一个字符串中搜索给定的子字符串,然后返回字符串的位置(没有找到,则返回-1)。区别在于:indexOf()方法从字符串的开头向后搜索子字符串,而lastIndexOf()方法是从字符串的末尾向前搜索子字符串。
var stringValue = "hello world";
alert(stringValue.indexOf("o")); //4
alert(stringValue.lastIndexOf("o"); //7
这两个方法都接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。indexOf()会从该参数指定的位置向后搜索;而lastIndexOf()则会从指定的位置向前搜索。
var stringValue = "hello world";
alert(stringValue.indexOf("o", 6)); //7
alert(stringValue.lastIndexOf("o", 6)); //4
在使用第二个参数的情况下,可以通过循环调用indexOf()或lastIndexOf()来找到所有匹配的子字符串。
var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var positions = new Array();
var pos = stringValue.index("e");
while(pos > -1) {
positions.push(pos);
pos = stringValue.indexOf("e", pos + 1);
}
alert(positions); //"3, 24, 32, 35, 52"
4.trim()方法
trim()方法会创建一个字符串的副本,删除前置及后缀的所有空格,然后返回结果。
var stringValue = " hello world ";
var trimmedStringValue = stringValue.trim();
alert(stringValue); //" hello world "
alert(trimmedStringValue); // "hello world"
5.字符串大小写转换方法
ECMAScript中涉及字符串大小写转换的方法有4个:toLowerCase()、toLocaleLowerCase()、toUpperCase()和toLocaleUpperCase()。
其中,toLowerCase()和toUpperCase()是两个经典的方法。而toLocaleLowerCase()和toLocaleUpperCase()方法则是针对特定地区的实现。
var stringValue = "hello world";
alert(stringValue.toLocaleUpperCase()); //"HELLO WORLD"
alert(stringValue.toUpperCase()); //"HELLO WORLD"
alert(stringValue.toLocaleLowerCase()); //"hello world"
alert(stringValue.toLowerCase()); //"hello world"
一般来说,在不知道自己的代码将在那种语言环境中运行的情况下,还是使用针对地区的方法更稳妥一些。
6.字符串的模式匹配方法
第一个方法是match(),在字符串上调用这个方法,本质上与调用RegExp的exec()方法相同。match()方法只接受一个参数,要么是一个正则表达式,要么是一个RegExp对象。
var text = "cat, bat, sat, fat";
var pattern = /.at/;
var matches = text.match(pattern);
alert(matches.index); //0
alert(matches[0]); //"cat"
alert(pattern.lastIndex); //0
match()方法返回一个数组,数组中的第一项是与模式匹配的字符串,之后的每一项(如果有)保存着与正则表达式中的捕获组匹配的字符串。
另一个用于查找模式的方法是search()。这个方法的唯一参数与match()方法的参数相同:由字符串或RegExp对象指定的一个正则表达式。search()方法返回字符串中第一个匹配项的索引;如果没有找到匹配项,则返回-1。而且,search()方法始终是从字符串开头向后查找模式。
var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
alert(pos); //1
例子中的search()方法返回1,即"at"在字符串中第一次出现的位置。
替换字符串的操作,ECMAScript提供了replace()方法。这个方法接收两个参数:第一个参数可以是一个RegExp对象或者一个字符串(这个字符串不会被转换成正则表达式),第二个参数可以是一个字符串或者一个函数。如果第一个参数是字符串,那么只会替换掉第一个子字符串。要想替换所有子字符串,唯一的办法是提供一个正则表达式,而且要指定全局(g)标志。
var text = "cat, bat, sat, fat";
var result = text.replace("at", "ond");
alert(result); //"cond, bat, sat, fat"
result = text.replace(/at/g, "ond");
alert(result); //"cond, bond, sond, fond"
如果第二个参数是字符串,那么还可以使用一些特殊的字符序列,将正则表达式操作得到的值插入到结果字符串中。下表列出了ECMAScript提供的这些特殊的字符序列。
字符序列 | 替换文本 |
---|---|
$$ | $ |
$& | 匹配整个模式的子字符串。与RegExp.lastMatch的值相同 |
$’ | 匹配的子字符串之前的子字符串。与RegExp.leftContext的值相同 |
$` | 匹配的子字符串之后的子字符串。与RegExp.rightContext的值相同 |
$n | 匹配第n个捕获组的子字符串,其中n等于0~9。例如,$1是匹配第1个捕获组的子字符串,$2是匹配第2个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串 |
$nn | 匹配第nn个捕获组的子字符串,其中nn等于01~99。例如,$01是匹配第1个捕获组的子字符串,$02是匹配第2个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串 |
通过这些特殊的字符序列,可以使用最近一次匹配结果中的内容。
var text = "cat, bat, sat, fat";
result = text.replace(/(.at)/g, "word($1)");
alert(result); //word (cat), word (bat), word (sat), word (fat)
在此,每个以"at"结尾的单词都被替换了,替换结果是"word"后跟一对圆括号,而圆括号中是被字符序列$1所替换的单词。
replace()方法的第二个参数也可以是一个函数。在只有一个匹配项(即与模式匹配的字符串)的情况下,会向这个函数传递3个参数:模式的匹配项、模式匹配项在字符串中的位置和原始字符串。在正则表达式中定义了多个捕获组的情况下,传递给函数的参数依次是模式的匹配项、第一个捕获组的匹配项、第二个捕获组的匹配项······,但最后两个参数仍然分别是模式的匹配项在字符串中的位置和原始字符串。这个函数返回一个字符串,表示应该被替换的匹配项使用函数作为replace()方法的第二个参数可以实现更加精细的替换操作。
function htmlEscape(text) {
return text.replace(/[<>"&]/g, function(match, pos, originalText) {
switch(match) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "\"":
return """;
}
});
}
alert(htmlEscape("<p class=\"greeting\">Hello world!</p>"));
//<p class="greeting">Hello world!</p>
split()方法,可以基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组中。分隔符可以是字符串,也可以是一个RegExp对象(这个方法不会将字符串看成正则表达式)。split()方法可以接受可选的第二个参数,用于指定数组的大小,以便确保返回的数组不会超过既定的大小。
var colorText = "red, blue, green, yellow";
var colors1 = colorText.split(",") //["red", "blue", "green", "yellow"]
var colors2 = colorText.split(",", 2); //["red", "blue"]
var colors3 = colorText.split(/[^\,]+/); //["", ",", ", ", ",", ""]
7.localeCompare()方法
localeCompare()方法比较两个字符串,并返回下列值中的一个:
1.如果字符串在字母表中应该排在字符串参数之前,则返回一个负数(大多数情况下是-1,具体的值要视实现而定);
2.如果字符串等于字符参数,则返回0;
3.如果字符串在字母表中应该排在字符串参数之后,则返回一个正数(大多数情况下是1,具体的值同样要视实现而定);
var stringValue = "yellow";
alert(stringValue.localeCompare("brick")); //1
alert(stringValue.localeCompare("yellow")); //0
alert(stringValue.localeCompare("zoo")); //-1
在强调一次,因为localeCompare()返回的数值取决于实现,所以最好是像下面例子所示的这样使用这个方法。
function determineOrder(value) {
var result = stringValue.localeCompare(value);
if(result < 0) {
alert("The string 'yellow' comes before the string '" + value + "'.");
} else if(result > 0) {
alert("The string 'yellow' comes after the string '" + value + "'.");
} else {
alert("The string 'yellow' is equal to the string '" + value + "'.");
}
}
determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");
localeCompare()方法比较与众不同的地方,就是实现所支持的地区(国家和语言)决定了这个方法的行为。
8.fromCharCode()方法
String构造函数本身还有一个静态方法:fromCharCode()。这个方法的任务是接收一或多个字符编码,然后将它们转换成一个字符串。从本质上看,这个方法与实例方法charCodeAt()执行的是相反的操作。
alert(String.fromCharCode(104, 101, 108, 108, 111)); //"hello"
在这里,给fromCharCode()传递的是字符串"hello"中每个字母的字符编码。