JavaScript String 方法大全
String方法大全:charAt/charCodeAt/at(index负索引)/includes/startsWith/endsWith/padStart/padEnd/repeat/slice/replace/replaceAll/match/matchAll/search/toUpperCase/toLowerCase/trim/split/localeCompare/concat · 难度:入门 · +10XP
JavaScript String 方法大全 —— 字符串操作速查
JavaScript字符串有30+个方法,掌握这些方法可以大幅提升你的开发效率。这里是最实用的速查。
最常用的10个
'hello'.charAt(0); // 'h'
'hello'.includes('ell'); // true
'hello'.startsWith('he'); // true
'hello'.endsWith('lo'); // true
'hello'.indexOf('l'); // 2
'hello'.slice(1, 4); // 'ell'
'hello'.replace('l', 'L'); // 'heLlo'
'hello'.toUpperCase(); // 'HELLO'
'hello'.toLowerCase(); // 'hello'
' hello '.trim(); // 'hello'
'5'.padStart(3, '0'); // '005'
'hello'.repeat(3); // 'hellohellohello'
'hello world'.split(' '); // ['hello', 'world']动手练习
- 基础练习:写一个"隐藏手机号中间4位"的函数——13812345678→138****5678。
- 进阶应用:用padStart格式化时间——5→05。
- 项目实战:用字符串方法实现一个简单的模板引擎。