js的字符串方法(1)

字符串长度

length 属性返回字符串的长度:

1 var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2 var sln = txt.length;

查找字符串中的字符串

indexOf() 方法返回字符串中指定文本首次出现的索引(位置):

1 var str = "The full name of China is the People's Republic of China.";
2 var pos = str.indexOf("China");

JavaScript 从零计算位置。

0 是字符串中的第一个位置,1 是第二个,2 是第三个 ...

lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引:

1 var str = "The full name of China is the People's Republic of China.";
2 var pos = str.lastIndexOf("China");

如果未找到文本, indexOf() 和 lastIndexOf() 均返回 -1。

1 var str = "The full name of China is the People's Republic of China.";
2 var pos = str.indexOf("USA");

两种方法都接受作为检索起始位置的第二个参数。

1 var str = "The full name of China is the People's Republic of China.";
2 var pos = str.indexOf("China", 18);

lastIndexOf() 方法向后进行检索(从尾到头),这意味着:假如第二个参数是 50,则从位置 50 开始检索,直到字符串的起点。

1 var str = "The full name of China is the People's Republic of China.";
2 var pos = str.lastIndexOf("China", 50);

检索字符串中的字符串

search() 方法搜索特定值的字符串,并返回匹配的位置:

1 var str = "The full name of China is the People's Republic of China.";
2 var pos = str.search("locate");

slice() 提取字符串的某个部分并在新字符串中返回被提取的部分。

该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。

1 var str = "Apple, Banana, Mango";
2 var res = str.slice(7,13);

res 的结果是:

Banana

如果某个参数为负,则从字符串的结尾开始计数。

这个例子裁剪字符串中位置 -12 到位置 -6 的片段:

1 var str = "Apple, Banana, Mango";
2 var res = str.slice(-13,-7);

res 的结果是:

Banana

substring() 类似于 slice()。

不同之处在于 substring() 无法接受负的索引。

1 var str = "Apple, Banana, Mango";
2 var res = str.substring(7,13);

res 的结果是:

Banana
原文地址:https://www.cnblogs.com/qdjj/p/12389803.html