详解JavaScript的String

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(二)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值