Kita'asa Yantara Karin JavaScript
String methods help you handle strings.
String methods and properties
Primitive values, such as "Bill Gates", cannot have properties and methods (because they are not objects).
But through JavaScript, methods and properties can also be used for primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String length
length
The property returns the length of the string:
实例
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;
Search for a string in a string
indexOf()
The method returns the specified text in the stringFirstOccurrence index (position):
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("China");
JavaScript counts positions from zero.
0 is the first position in the string, 1 is the second, 2 is the third ...
lastIndexOf()
The method returns the specified text in the stringFinallyIndex of one occurrence:
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.lastIndexOf("China");
If the text is not found indexOf()
And lastIndexOf()
Both return -1.
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("USA");
Both methods accept the second parameter as the search starting position.
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("China", 18);
lastIndexOf()
Method searches backward (from tail to head), which means: if the second parameter is 50, it starts searching from position 50 until the start of the string.
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.lastIndexOf("China", 50);
Search for a string in a string
search()
Method to search for a specific value string and return the match position:
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.search("locate");
Kai gudan ba? A?i?
两种方法,indexOf()
与 search()
,是相等的。
这两种方法是不相等的。区别在于:
- search() 方法无法设置第二个开始位置参数。
- indexOf() 方法无法设置更强大的搜索值(正则表达式)。
您将在正则表达式的章节学习到这些更强大的检索值。
提取部分字符串
有三种提取部分字符串的方法:
- slice(start, end)
- substring(start, end)
- substr(start, length)
slice() 方法
slice()
提取字符串的某个部分并在新字符串中返回被提取的部分。
该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。
这个例子裁剪字符串中位置 7 到位置 13 的片段:
实例
var str = "Apple, Banana, Mango"; var res = str.slice(7,13);
res 的结果是:
Banana
如果某个参数为负,则从字符串的结尾开始计数。
这个例子裁剪字符串中位置 -12 到位置 -6 的片段:
实例
var str = "Apple, Banana, Mango"; var res = str.slice(-13,-7);
res 的结果是:
Banana
如果省略第二个参数,则该方法将裁剪字符串的剩余部分:
实例
var res = str.slice(7);
或者从结尾计数:
实例
var res = str.slice(-13);
提示:负值位置不适用 Internet Explorer 8 及其更早版本。
substring() 方法
substring()
类似于 slice()
。
不同之处在于 substring()
无法接受负的索引。
实例
var str = "Apple, Banana, Mango"; var res = str.substring(7,13);
res 的结果是:
Banana
如果省略第二个参数,则该 substring()
将裁剪字符串的剩余部分。
substr() 方法
substr()
类似于 slice()
。
不同之处在于第二个参数规定被提取部分的长度。
实例
var str = "Apple, Banana, Mango"; var res = str.substr(7,6);
res 的结果是:
Banana
如果省略第二个参数,则该 substr() 将裁剪字符串的剩余部分。
实例
var str = "Apple, Banana, Mango"; var res = str.substr(7);
res 的结果是:
Banana, Mango
如果首个参数为负,则从字符串的结尾计算位置。
实例
var str = "Apple, Banana, Mango"; var res = str.substr(-5);
res 的结果是:
Mango
第二个参数不能为负,因为它定义的是长度。
替换字符串内容
replace()
方法用另一个值替换在字符串中指定的值:
实例
str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3School");
replace()
方法不会改变调用它的字符串。它返回的是新字符串。
默认地,replace()
只替换首个匹配:
实例
str = "Please visit Microsoft and Microsoft!"; var n = str.replace("Microsoft", "W3School");
默认地,replace()
对大小写敏感。因此不对匹配 MICROSOFT:
实例
str = "Please visit Microsoft!"; var n = str.replace("MICROSOFT", "W3School");
如需执行大小写不敏感的替换,请使用正则表达式 /i
(大小写不敏感):
实例
str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3School");
请注意正则表达式不带引号。
如需替换所有匹配,请使用正则表达式的 g
标志(用于全局搜索):
实例
str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3School");
您将在 JavaScript 正则表达式这一章学到更多有关正则表达式的内容。
转换为大写和小写
通过 toUpperCase()
把字符串转换为大写:
实例
var text1 = "Hello World!"; // 字符串 var text2 = text1.toUpperCase(); // text2 是被转换为大写的 text1
通过 toLowerCase()
把字符串转换为小写:
实例
var text1 = "Hello World!"; // 字符串 var text2 = text1.toLowerCase(); // text2 是被转换为小写的 text1
concat() 方法
concat()
连接两个或多个字符串:
实例
var text1 = "Hello"; var text2 = "World"; text3 = text1.concat(" ",text2);
concat()
方法可用于代替加运算符。下面两行是等效的:
实例
var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ","World!");
所有字符串方法都会返回新字符串。它们不会修改原始字符串。
官方说法:字符串是不可变的:字符串不能更改,只能替换。
String.trim()
trim()
方法删除字符串两端的空白符:
实例
var str = " Hello World! "; alert(str.trim());
警告:Internet Explorer 8 或更低版本不支持 trim()
方法。
如需支持 IE 8,您可搭配正则表达式使用 replace()
方法代替:
实例
var str = " Hello World! "; alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));
您还可以使用上面的 replace 方案把 trim 函数添加到 JavaScript String.prototype:
实例
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; var str = " Hello World! "; alert(str.trim());
提取字符串字符
这是两个提取字符串字符的安全方法:
- charAt(position)
- charCodeAt(position)
charCodeAt() 方法
charCodeAt()
方法返回字符串中指定索引的字符 unicode 编码:
实例
var str = "HELLO WORLD"; str.charCodeAt(0); // 返回 72
属性访问(Property Access)
ECMAScript 5 (2009) 允许对字符串的属性访问 [ ]:
实例
var str = "HELLO WORLD"; str[0]; // 返回 H
使用属性访问有点不太靠谱:
- 不适用 Internet Explorer 7 或更早的版本
- 它让字符串看起来像是数组(其实并不是)
- 如果找不到字符,
[ ]
返回undefined
,而charAt()
返回空字符串。 - 它是只读的。
str[0] = "A"
不会产生错误(但也不会工作!)
实例
var str = "HELLO WORLD"; str[0] = "A"; // 不产生错误,但不会工作 str[0]; // 返回 H
提示:如果您希望按照数组的方式处理字符串,可以先把它转换为数组。
把字符串转换为数组
可以通过 split()
将字符串转换为数组:
实例
var txt = "a,b,c,d,e"; // 字符串 txt.split(","); // 用逗号分隔 txt.split(" "); // 用空格分隔 txt.split("|"); // 用竖线分隔
如果省略分隔符,被返回的数组将包含 index [0] 中的整个字符串。
如果分隔符是 "",被返回的数组将是间隔单个字符的数组:
实例
var txt = "Hello"; // 字符串 txt.split(""); // 分隔为字符