高程笔记-String

《JavaScript高级程序》笔记,包含字符串常用方法。

创建方式

  • 构造函数var str = new String('hello');
  • 字面量方式var str = 'hello';

字符方法

charAt():返回在指定位置的字符。
charCodeAt():返回在指定的位置的字符的 Unicode 编码。

concat():连接字符串。
substr(start[, length]):通过指定字符数返回在指定位置开始的字符串中的字符。
substring(indexStart[, indexEnd]):返回在字符串中指定两个下标之间的字符。
slice(beginSlice[, endSlice]):提取字符串的片断,并在新的字符串中返回被提取的部分。

indexOf():检索字符串。
lastIndexOf():从后向前搜索字符串。

trim():一个字符串的两端删除空白字符。

match():找到一个或多个正则表达式的匹配。
replace():替换与正则表达式匹配的子串。
search():检索与正则表达式相匹配的值。

split():分离字符串成字串,将字符串对象分割成字符串数组。

localeCompare():返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。

toLowerCase():把字符串转换为小写。
toUpperCase():把字符串转换为大写。
toLocaleLowerCase():根据当前区域设置,把字符串转换为小写。
toLocaleUpperCase():根据当前区域设置,把字符串转换为大写。

fromCharCode():从字符编码创建一个字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var stringValue="hello world";

stringValue.charAt(1);// "e"
stringValue.charCodeAt(1); // 101

stringValue.concat('!!!'); // "hello world!!!"
stringValue.substr(1,2); // "el"
stringValue.substring(1,2); // "e"
stringValue.slice(1,2); // "e"

stringValue.indexOf("o"); // 4
stringValue.lastIndexOf("o"); // 7

var stringVal="yellow";
stringVal.localeCompare("brick"); // 1
stringVal.localeCompare("yellow"); // 0
stringVal.localeCompare("zoo"); // -1
------本文结束 感谢阅读------