字符串常用方法

1. substring()

字符串截取,接收2个参数,前闭后开,不改变原字符串

let str = "你好,中国!我们伟大的母亲";
const res = str.substring(0, 2); // 你好

2.slice()

字符串截取,接收2个参数,前闭后开,不改变原字符串

let str = "hello,china";
const res = str.slice(0, 2); // he

3.split()

字符串转数组

let str = "你好,中国!我们伟大的母亲";
const res = str.split(""); // ['你', '好', ',', '中', '国', '!', '我', '们', '伟', '大', '的', '母', '亲']

4.replace()

替换,从前往后,替换第一个符合的,返回一个新的字符串

let str = "你好,中国!我们伟大的母亲";      
const res = str.replace('你好', "hello"); // hello,中国!我们伟大的母亲
//                       旧值    新值

第一个参数值可以是一个正则

let str = "你好,中国!你好,我们伟大的母亲,你好";
const res = str.replace(/你好/g, "hello"); // hello,中国!我们伟大的母亲
//                       旧值    新值

5.replaceAll()

替换所有符合条件的元素

let str = "hello,china";
const res = str.replaceAll("h", "x"); // xello,cxina

6.trim()

去除首尾的空格

let str = " 你好,中国 ! 我们 伟大的 母亲 ";
const res = str.trim(); // '你好,中国 ! 我们 伟大的 母亲'

7.toUpperCase()

小写转大写

let str = "hello,china";
const res = str.toUpperCase(); // HELLO,CHINA

8.toLocaleLowerCase()

大写转小写

let str = "HELLO,CHINA";
const res = str.toLocaleLowerCase(); // hello,china

9.charAt()

获取指定位置的字符

let str = "hello,china";
const res = str.charAt(6); // c

10.charCodeAt()

获取指定位置的字符的Unicode 编码

let str = "Ahello,china";
const res = str.charCodeAt(0); // 65

11.includes()

是否包含某字符,存在:true,不存在:false

let str = "hello,china";
const res = str.includes("he"); // true

12.indexOf()

判断是否包含某字符,存在:返回索引,不存在:-1

let str = "hello,china";
const res = str.indexOf("ll"); // 2

13.startsWith()

以什么开头

 let str = "hello,china";
 const res = str.startsWith("h"); // true

14.endsWith()

以什么结尾

let str = "hello,china";
const res = str.endsWith("h"); // false
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值