1、概念

String 对象用于处理文本(字符串)
String 对象创建方法: new String()

语法:var name = new String(“hello”) 等同于 var name = “hello”

2、String 对象属性

2.1 constructor 对创建该对象的函数的引用

var name = "hello"
console.log(name.constructor); // [Function: String]
console.log(name.constructor()); //

2.2 length 字符串的长度

var name = "hello"
console.log(name.length); // 5

2.3 prototype 允许您向对象添加属性和方法

String.prototype.fristChar = function () {
if (this.length <= 1) {
return this
} else {
return this.charAt(0)
}
}
var name = "hello"
console.log(name.fristChar()); // h

3、String 对象方法

3.1 charAt() 返回在指定位置的字符

var name = "hello"
console.log(name.charAt(1)); // e

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

var name = "hello"
console.log(name.charCodeAt(1)); // 101

3.3 concat() 连接两个或更多字符串并返回新的字符串

var name = "hello"
console.log(name.concat(' world')); // hello world
console.log(name.concat(' world', ' a', ' b')); // hello world a b
console.log(name.concat(' world', [' a', ' b'])); // hello world a, b

3.4 fromCharCode() 将 Unicode 编码转为字符

var aStr = String.fromCharCode(65);
console.log(aStr); // A

3.5 indexOf() 返回某个指定的字符串值在字符串中首次出现的位置

var name = "hello"
console.log(name.indexOf('h')); // 0
console.log(name.indexOf('l')); // 2

3.6 lastIndexOf() 从后向前搜索字符串

var name = "hello"
console.log(name.lastIndexOf('h')); // 0
console.log(name.lastIndexOf('l')); // 3

3.7 match() 查找找到一个或多个正则表达式的匹配

var name = "hello"
console.log(name.match(/ll/g)); // [ 'll' ]
console.log(name.match(/dd/g)); // null

3.8 replace() 在字符串中查找匹配的子串并替换与正则表达式匹配的子串

var name = "hello"
console.log(name.replace("ll","tt")); // hetto
console.log(name); // hello

3.9 search() 查找与正则表达式相匹配的值

var name = "hello"
console.log(name.search("ll")); // 2
console.log(name.search("dd")); // -1

3.10 slice() 提取字符串的片断并在新的字符串中返回被提取的部分

var name = "hello"
console.log(name.slice(0,2)); // he
console.log(name.slice(1,2)); // e
console.log(name); // hello

3.11 split() 把字符串分割为字符串数组

var name = "hello"
console.log(name.split('e')); // [ 'h', 'llo' ]
console.log(name.split('l')); // [ 'he', '', 'o' ]
console.log(name); // hello

3.12 substr() 从起始索引号提取字符串中指定数目的字符

var name = "hello"
console.log(name.substr(0, 2)); // he
console.log(name.substr(1, 2)); // el
console.log(name); // hello

3.13 substring() 提取字符串中两个指定的索引号之间的字符

var name = "hello"
console.log(name.substring(0, 2)); // he
console.log(name.substring(1, 2)); // el
console.log(name); // hello

3.14 toLowerCase() 把字符串转换为小写

var name = "hEllo"
console.log(name.toLowerCase()); // hello

3.15 toUpperCase() 把字符串转换为大写

var name = "hEllo"
console.log(name.toUpperCase()); // HELLO

3.16 trim() 去除字符串两边的空白

var name = " hello "
console.log(name.trim());
console.log(name);
// hello
// hello

3.17 valueOf() 返回某个字符串对象的原始值

var name = "hello"
console.log(name.valueOf());
console.log(name);
// hello
// hello