js 字符串处理

1. 返回指定索引的字符(charAt)
let str = '123456789';
let vIndex = str.charAt(1);
console.log(vIndex);
// 2

2. 拼接字符串
const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2));
// "Hello World"

console.log(str2.concat(', ', str1));
// "World, Hello"

3. 复制字符串
let str = 'HelloWorld'
str.repeat(2) 
// HelloWorld HelloWorld 复制一遍 数字为几代表复制几遍

4. 判断一个字符串是否以指定字符串开始
const str = 'Cats are the best!';
console.log(str.endsWith('Cats'));
// true

5. 判断一个字符串是否以指定字符串结尾
const str = 'Cats are the best!';
console.log(str.endsWith('best!'));
// true

6. 翻转字符串
let str = 'HelloWorld'
let ary = str.split('')
str = ary.reverse().join('')
console.log(str)
//dlroWolleH

7. 转换大小写
let str = 'HelloWorld'
str.toUpperCase()   
// 'HELLOWORLD'
str.toLowerCase()   
// 'helloworld'

8. 字符串的右侧/左侧开始填充
const str1 = '5';
console.log(str1.padStart(2, '0'));
// 05
console.log(str1.padEnd(2, '0'));
// 50

9. 替换字符串中的部分
const str1 = 'Hello,World';
console.log(str1.replace(',', '-'))
// Hello-World
const mac = '00:11:22:33:44:55';
console.log(mac.replace(/:/g, ""));
// 001122334455

10. 查询字符串位置indexOf、lastIndexOf、Search
const str = 'helloWorld'
str.indexOf('l')   
// 2  返回第一次出现的位置索引
str.lastIndexOf('o')   
// 6  返回最后一次出现的位置索引
str.search(/[A-Z]/g)
// 5 W 根据正则表达式匹配索引
str.search(/[.]/g)
// -1 匹配不到返回-1

11. 截取字符串
const str = 'HelloWorld'
// 从索引n开始,截取m个字符
substr(n,m)
// 从索引n开始,截取到索引m,不包括m.将截取的字符返回
substring(n,m)
// 从索引n开始,截取到索引m,不包括m.
slice(n,m)

12. 字符串的两端清除空格
const greeting = '   Hello world!   ';
console.log(greeting.trim());
// "Hello world!"

13. 去除字符串末尾空格
// trimEnd() 方法会删除字符串末尾的空白字符。
// trimRight() 是这个方法的别名
const greeting = '   Hello world!   ';
console.log(greeting.trimEnd());
//"   Hello world!";

14. 查找是否存在某个字符
const str = 'HelloWorld'
console.log(str.includes('W'))
// true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值