String是对应字符串的引用类型。由16位码元(code unit)组成。对多数字符来说,每16位码元对应一个字符。可以通过new构造函数创建,也可以通过字面量的方式创建。
let string = new String("hello")//new 创建
let test = "hello"//字面量创建
一、length属性
字符串中字符的数量(长度)。
let string = "hello world";
console.log(string.length); //11
二、chart()
返回给定索引位置的字符,由传给方法的整数参数指定
let string = "hello world";
console.log(string.chart(0)); // "h"
三、拼接字符串
目前有concat()、( + )号拼接、模板字符串三种方式
1、concat()
用于将一个或多个字符串拼接成一个新字符串
let string = "hello ";
let result = string.concat("world");
console.log(result); // "hello world"
console.log(string); // "hello"
2、( + )号拼接
let string = "hello ";
let result = string + "world";
console.log(result); // "hello world"
console.log(string); // "hello"
3、模板字符串
模板字符串用两个反引号**`**表示,里面的变量用 **${}**来装
let string = "hello ";
let result = `${string}world`;
console.log(result); // "hello world"
console.log(string); // "hello"
四、提取字符串
1、slice()
let string = "hello world";
console.log(string.slice(3)); // "lo world"
2、substr()
let string = "hello world";
console.log(string.substr(3)); // "lo world"
3、substring()
let string = "hello world";
console.log(string.substring(3)); // "lo world"
上面的**slice()和substring()**提取方法只接受两个参数(可选)。如果只传入一个参数,未传第二个参数,则从传入的第一个参数开始提取,直至结尾;若传了第二个参数,则只提取第一个参数到第二个参数间的字符。
**substr()**也只接受两个参数(可选)。只传入一个参数,未传第二个参数,则从传入的第一个参数开始提取,直至结尾;它的第二个参数代表它需要返回的字符长度
let string = "hello world";
console.log(string.slice(3, 7)); // "lo w"
console.log(string.substring(3,7)); // "lo w"
console.log(string.substr(3, 7)); // "lo worl"
本篇完结!
篇幅过多,剩余部分请前往主页查看,文章标题为:详解
JavaScript的String(二)