js的字符串方法(3)

trim() 方法删除字符串两端的空白符:

1 var str = "       Hello World!        ";
2 alert(str.trim());

需要注意的是Internet Explorer 8 或更低版本不支持 trim() 方法。

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

1 var str = "       Hello World!        ";
2 alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

这是两个提取字符串字符的安全方法:

charAt(position)

charCodeAt(position)

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

1 var str = "HELLO WORLD";
2 str.charAt(0);            // 返回 H

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

1 var str = "HELLO WORLD";
2 
3 str.charCodeAt(0);         // 返回 72

属性访问(Property Access)

ECMAScript 5 (2009) 允许对字符串的属性访问 [ ]:

1 var str = "HELLO WORLD";
2 str[0];                   // 返回 H

把字符串转换为数组

可以通过 split() 将字符串转换为数组:

1 var txt = "a,b,c,d,e";   // 字符串
2 txt.split(",");          // 用逗号分隔
3 txt.split(" ");          // 用空格分隔
4 txt.split("|");          // 用竖线分隔

如果省略分隔符,被返回的数组将包含 index [0] 中的整个字符串。

如果分隔符是 "",被返回的数组将是间隔单个字符的数组:

1 var txt = "Hello";       // 字符串
2 txt.split("");    

 

var str = "HELLO WORLD";
str.charAt(0);            // 返回 H
posted @ 2020-03-02 13:18  我有头盔  阅读(160)  评论(0编辑  收藏  举报