字符串操作
JavaScript 字符串常用操作方法。
字符串拼接
// 传统拼接
const str1 = 'Hello' + ' ' + 'World';
// 模板字符串(推荐)
const name = 'Alice';
const str2 = `Hello, ${name}!`;
// join 拼接数组
const arr = ['a', 'b', 'c'];
const str3 = arr.join('-'); // 'a-b-c'
字符串截取
const str = 'Hello World';
// slice
str.slice(0, 5); // 'Hello'
str.slice(-5); // 'World'
str.slice(6, 11); // 'World'
// substring
str.substring(0, 5); // 'Hello'
str.substring(6); // 'World'
// substr (已废弃,不推荐)
str.substr(0, 5); // 'Hello'
字符串查找
const str = 'Hello World';
// indexOf
str.indexOf('o'); // 4
str.indexOf('o', 5); // 7
str.indexOf('x'); // -1
// includes (推荐)
str.includes('World'); // true
str.includes('world'); // false (区分大小写)
// startsWith / endsWith
str.startsWith('Hello'); // true
str.endsWith('World'); // true
// match (正则)
str.match(/o/g); // ['o', 'o']
str.match(/world/i); // ['World']
字符串替换
const str = 'Hello World';
// replace (只替换第一个)
str.replace('World', 'JavaScript'); // 'Hello JavaScript'
// replaceAll (全部替换)
str.replaceAll('o', '0'); // 'Hell0 W0rld'
// replace 正则
str.replace(/o/g, '0'); // 'Hell0 W0rld'
str.replace(/\b\w/g, m => m.toUpperCase()); // 'Hello World'
字符串分割
const str = 'a,b,c,d';
// split
str.split(','); // ['a', 'b', 'c', 'd']
str.split(',', 2); // ['a', 'b']
// 按分隔符分割
'a b c'.split(' '); // ['a', 'b', 'c']
大小写转换
const str = 'Hello World';
// toUpperCase
str.toUpperCase(); // 'HELLO WORLD'
// toLowerCase
str.toLowerCase(); // 'hello world'
// 首字母大写
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
capitalize('hello'); // 'Hello'
// 每个单词首字母大写
function titleCase(str) {
return str.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
titleCase('hello world'); // 'Hello World'
去除空白
const str = ' Hello World ';
// trim
str.trim(); // 'Hello World'
str.trimStart(); // 'Hello World '
str.trimEnd(); // ' Hello World'
// 去除所有空白
str.replace(/\s+/g, ''); // 'HelloWorld'
字符串重复
'ha'.repeat(3); // 'hahaha'
'-'.repeat(10); // '----------'
填充字符串
'5'.padStart(3, '0'); // '005'
'5'.padEnd(3, '0'); // '500'
'hello'.padStart(10, '*'); // '*****hello'
常用工具函数
// 截断字符串
function truncate(str, length, suffix = '...') {
if (str.length <= length) return str;
return str.slice(0, length - suffix.length) + suffix;
}
truncate('Hello World', 8); // 'Hello...'
// 生成随机字符串
function randomString(length = 8) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
// 转义 HTML
function escapeHtml(str) {
const html = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str.replace(/[&<>"']/g, c => html[c]);
}