美文网首页
字符串的常用方法

字符串的常用方法

作者: 沃德麻鸭 | 来源:发表于2021-10-19 19:38 被阅读0次

1.length

属性返回字符串的长度

2.indexOf()

方法返回字符串中指定文本首次 出现的索引值

(如果未找到文本, indexOf() 和 lastIndexOf() 均返回 -1。两种方法都接受作为检索起始位置的第二个参数。)

var str = "The full name of China is the People's Republic of China.";

var pos = str.indexOf("China", 18);    //  输出结果为  51 ,h为下标18,C为下标51

3.lastIndexOf()

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

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

var str = "The full name of China is the People's Republic of China.";

var pos = str.lastIndexOf("China", 50);  //  运行结果为  17

4.search()

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

两种方法,indexOf() 与 search(),是相等

这两种方法是不相等的区别在于:

search() 方法无法设置第二个开始位置参数。

indexOf() 方法无法设置更强大的搜索值(正则表达式)。

5.slice()

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

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

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

③如果省略第二个参数,则该方法将裁剪字符串的剩余部分,为负一样也要从结尾开始计数,数到对应位置往后截取

var str = "Apple, Banana, Mango";

var res = str.slice(-13);  //  Banana, Mango    与 var res = str.slice(7)  截取结果相同

最后的位置字符不计入在内

6.substring()

substring() 类似于 slice()。

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

7.substr()

substr() 类似于 slice()。

该方法设置两个参数:起始索引(开始位置),截取长度

不同之处在于第二个参数规定被提取部分的长度

8.replace()

方法用另一个值替换在字符串中指定的值, replace() 方法不会改变调用它的字符串。它返回的是新字符串

默认地,replace() 只替换首个匹配

9.toUpperCase()

把字符串转换为大写

10.toLowerCase()

把字符串转换为小写

11.concat()

concat() 连接两个或多个字符串,concat() 方法可用于代替加运算符。

var text = "Hello" + " " + "World!";

var text = "Hello".concat(" ","World!");

两种方法等效 //  Hello World!

12.trim()

删除字符串两端的空白符-----Internet Explorer 8 或更低版本不支持 trim() 方法。

var str = "      Hello World!        ";

alert(str.trim());

如需支持 IE 8,可搭配正则表达式使用 replace() 方法代替

var str = "      Hello World!        ";

alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

13.charAt()

charAt() 方法返回字符串中指定下标(位置)的      字符串

var str = "HELLO WORLD";

str.charAt(0);    // 返回 H

14.charCodeAt()

charCodeAt() 方法返回字符串中指定索引的字符 unicode    编码

var str = "HELLO WORLD";

str.charCodeAt(0);    // 返回 72,也就是说H对应的编码是72

15.split()

可以通过 split() 将字符串转换为数组,然后就能够调用数组的方法

var txt = "a,b,c,d,e";  // 字符串

txt.split(",");          // 在逗号处分隔

txt.split(" ");          // 在空格分隔

txt.split("");          // 每一个单位都要进行分隔

16.repeat()

参数为数字类型,使用方法是  字符串.repeat()  用来将字符串重复几次,例如:'x'.repeat(2), 打印结果就是 'xx'

17.startsWith和endsWith

查看字符串是不是以  某字符串开头或结尾 ,结果返回布尔值

示例

相关文章

网友评论

      本文标题:字符串的常用方法

      本文链接:https://www.haomeiwen.com/subject/gtflgltx.html