一、构造函数
new String()是实例化字符串对象
String()是一个方法,返回字符串
new String()
const a = new String("Hello world"); // a === "Hello world" is false
console.log(a instanceof String) // true
console.log(typeof a) // object
String()
const b = String("Hello world"); // b === "Hello world" is true
console.log(b instanceof String) // is false
console.log(typeof b) // "string"
二、属性
length 是字符串的只读属性,包含字符串的长度
三、方法
一、split方法
split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。
let str = '123456789'
let arr = str.split("")
console.log(arr);
二、concat方法
concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。
let str1 = 'hello'
let str2 = 'world'
console.log(str1.concat(str2)); //helloworld
console.log(str1.concat(str2), '!', '~'); // helloworld ! ~
三、endsWith方法
endsWith() 方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false。
let str1 = 'hello'
console.log(str1.endsWith('o')); // true
console.log(str1.endsWith('lo')); // true
console.log(str1.endsWith('l')); // false
四、startsWith方法
startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。
let str1 = 'hello'
console.log(str1.startsWith('lo')); // false
console.log(str1.startsWith('he')); // true
console.log(str1.startsWith('h')); // true
五、indexOf方法
indexOf() 方法,给定一个参数:要搜索的子字符串,搜索整个调用字符串,并返回指定子字符串第一次出现的索引。给定第二个参数:一个数字,该方法将返回指定子字符串在大于或等于指定数字的索引处的第一次出现。
let str = 'hello world hello'
console.log(str.indexOf('o')); // 4
console.log(str.indexOf('o', 0)); // 4
// 第二个参数小于0,默认和0一样
console.log(str.indexOf('o', -5)); // 4
// 第一次大于等于6的位置
console.log(str.indexOf('o', 6)); // 7
console.log(str.indexOf('o', 12)); // 16
// 18大于字符串长度,所以返回-1
console.log(str.indexOf('o', 18)); // -1
六、includes方法
includes() 方法执行区分大小写的搜索,以确定是否可以在另一个字符串中找到一个字符串,并根据情况返回 true 或 false。
let str = 'hello world'
console.log(str.includes('o')); // true
console.log(str.includes('O')); // false
console.log(str.includes('o', 4)); // true