String方法总结

一、构造函数

new String()是实例化字符串对象

String()是一个方法,返回字符串

  1. new String()

const a = new String("Hello world"); // a === "Hello world" is false
console.log(a instanceof String) // true
console.log(typeof a)  // object
  1. 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

七、

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奶粉罐没粉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值