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
js 字符串处理
最新推荐文章于 2023-11-08 11:26:25 发布