JavaScript高级程序设计第5章读书笔记(16)
字符串位置方法
有两个方法可以从字符串中查找字符串,indexOf()
和lastIndexOf()
。它们都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置(如果没有找到该子字符串,则返回-1)。它们的区别在于,indexOf()方法从字符串的开头向后搜索子字符串,而lastIndexOf()方法是从字符串的末尾向前搜索子字符串。
1 2 3 4 |
var stringValue = "hello world"; alert(stringValue.indexOf("o")); // 4 alert(stringValue.lastIndexOf("o")); // 7 |
子字符串”o”第一次出现的位置是4,即”hello”中的”o”;最后一次出现的位置是7,即”world”中的”o”。如果”o”在这个字符串中只出现了一次,那么indexOf()和lastIndexOf()会返回相同的位置值。
这两个方法都可以接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。比如:
1 2 3 4 |
var stringValue = "hello world"; alert(stringValue.indexOf("o", 6)); // 7 alert(stringValue.lastIndexOf("o",6)); // 4 |
在使用第二个参数的情况下,我们可以通过循环调用indexOf()或lastIndexOf()来找到所有匹配的子字符串,比如:
1 2 3 4 5 6 7 8 9 10 11 |
var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"; var positions = new Array(); var pos = stringValue.indexOf("e"); while(pos > -1){ positions.push(pos); pos = stringValue.indexOf("e", pos+1); } alert(positions); // "3,24,32,35,52" |
trim()方法
ECMAScript 5为所有字符串定义了trim()方法。该方法会创建一个字符串的副本,删除前置以及后缀的所有空格,然后返回结果。比如:
1 2 3 4 5 6 |
var stringValue = " hello world "; var trimmedStringValue = stringValue.trim(); alert(stringValue); // " hello world "; alert(trimmedStringValue); // "hello world" |
trim()方法返回的是字符串的副本,因此,原始字符串不会被修改。支持该方法的浏览器有 IE9+、Firefox 3.5+、Safari 5+、Opera 10.5+和Chrome。此外,Firefox 3.5+、Safari 5+和Chrome 8+还支持非标准的trimLeft()
和trimRight()
方法,分别用于删除字符串开头和末尾的空格。
字符串大小写转换方法
ECMAScript中涉及字符串大小写转换的方法有4个:toLowerCase()
、toLocaleLowerCase()
、toUpperCase()
和toLocaleUpperCase()
。其中,toLowerCase()和toUpperCase()是两个经典方法,借鉴自java.lang.String中的同名方法。而toLocaleLowerCase()和toLocaleUpperCase()方法则是针对特定地区的实现。对有些地区来说,针对地区的方法和其通用方法得到的结果相同,但是少数语言(比如:土耳其语)会为Unicode大小写转换应用特殊的规则,这时候就必须使用针对地区的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var stringValue = "hello world"; alert(stringValue.toLocaleUpperCase()); // "HELLO WORLD" alert(stringValue.toUpperCase()); // "HELLO WORLD" alert(stringValue.toLocaleLowerCase()); // "hello world" alert(stringValue.toLowerCase()); // "hello world" |
以上示例代码,调用toLocaleUpperCase()
和toUpperCase()
的时候,得到的是相同的结果。一般来说,在无法确定自己的代码将在哪种语言环境中运行的时候,使用针对地区的方法会更稳妥。
字符串的模式匹配方法
String类型定义了几个用于在字符串中匹配模式的方法。第一个是match()
,在字符串上调用这个方法,本质上与调用RegExp的exec()
方法相同。match()方法只接收一个参数,要么是一个正则表达式,要么是一个RegExp对象。比如:
1 2 3 4 5 6 7 8 9 |
var text = "cat, bat, sat, fat"; var pattern = /.at/; // 与pattern.exec(text)相同 var matches = text.match(pattern); alert(matches.index); // 0 alert(matches[0]); // "cat" alert(pattern.lastIndex); // 0 |
本例中的match()方法返回一个数组;如果调用RegExp对象的exec()方法并传递本例中的字符串作为参数,也会得到相同的数组。数组的第一项是与整个模式匹配的字符串,之后的每一项(如果有)保存着与正则表达式中的捕获组匹配的字符串。
另外一个用于查找的方法是search()。它的唯一参数与match()方法的参数相同:由字符串或RegExp对象指定的一个正则表达式。search()方法返回字符串中第一个匹配项的索引;如果没有找到匹配项,则返回-1。而且,search()方法始终是从字符串开头向后查找模式。比如:
1 2 3 4 |
var text = "cat, bat, sat, fat"; var pos = text.search(/at/); alert(pos); // 1 |
本例中,search()返回1,即”at”在字符串中第一次出现的位置。