const str = "东巴文";
console.log(str.length); // 3
const str2 = "Hello";
console.log(str2.length); // 5
const str = "东巴文";
// 索引访问
console.log(str[0]); // "东"
console.log(str.charAt(0)); // "东"
// at方法(支持负索引)
console.log(str.at(0)); // "东"
console.log(str.at(-1)); // "文"
// charCodeAt:获取Unicode码点
console.log(str.charCodeAt(0)); // 19996
// codePointAt:获取完整码点(支持代理对)
console.log(str.codePointAt(0));
const str = "东巴文";
// for...of(推荐)
for (const char of str) {
console.log(char);
}
// 传统for循环
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
// 转为数组
const chars = [...str]; // ["东", "巴", "文"]
const chars2 = Array.from(str);
const str = "东巴文学习东巴文";
// indexOf:从前往后找
console.log(str.indexOf("东巴")); // 0
console.log(str.indexOf("东巴", 1)); // 4
// lastIndexOf:从后往前找
console.log(str.lastIndexOf("东巴")); // 4
// 未找到返回-1
console.log(str.indexOf("不存在")); // -1
const str = "东巴文学习";
console.log(str.includes("东巴")); // true
console.log(str.includes("学习")); // true
console.log(str.includes("不存在")); // false
// 从指定位置开始
console.log(str.includes("东巴", 1)); // false
const str = "东巴文学习";
// startsWith:是否以指定字符串开头
console.log(str.startsWith("东巴")); // true
console.log(str.startsWith("文", 2)); // true(从索引2开始)
// endsWith:是否以指定字符串结尾
console.log(str.endsWith("学习")); // true
console.log(str.endsWith("文", 3)); // true(到索引3为止)
| 方法 | 返回值 | 东巴文建议 |
|---|---|---|
| indexOf | 索引或-1 | 需要索引时 |
| includes | 布尔值 | 检查存在性 |
| startsWith | 布尔值 | 检查开头 |
| endsWith | 布尔值 | 检查结尾 |
const str = "东巴文学习";
// slice(start, end):不包含end
console.log(str.slice(0, 3)); // "东巴文"
console.log(str.slice(3)); // "学习"
console.log(str.slice(-2)); // "学习"
console.log(str.slice(1, -1)); // "巴文学"
const str = "东巴文学习";
// substring(start, end):不包含end
console.log(str.substring(0, 3)); // "东巴文"
console.log(str.substring(3)); // "学习"
// 与slice的区别:substring会自动调整参数顺序
console.log(str.substring(3, 0)); // "东巴文"(自动调整为0,3)
console.log(str.slice(3, 0)); // ""(返回空字符串)
// substring不支持负索引
console.log(str.substring(-2)); // "东巴文学习"(负数当作0)
const str = "东巴文学习";
// substr(start, length):从start开始,取length个字符
console.log(str.substr(0, 3)); // "东巴文"
console.log(str.substr(3, 2)); // "学习"
// 注意:substr已废弃,建议使用slice
| 方法 | 参数 | 负索引 | 东巴文建议 |
|---|---|---|---|
| slice | (start, end) | 支持 | 推荐 |
| substring | (start, end) | 不支持 | 兼容性好 |
| substr | (start, length) | 支持 | 已废弃 |
const str = "东,巴,文";
// 按分隔符分割
console.log(str.split(",")); // ["东", "巴", "文"]
// 限制分割数量
console.log(str.split(",", 2)); // ["东", "巴"]
// 空字符串分割为字符数组
console.log("东巴文".split("")); // ["东", "巴", "文"]
// 使用正则表达式
console.log("东巴 文学习".split(/\s/)); // ["东巴", "文学习"]
// 解析URL参数
const url = "name=东巴文&age=1";
const params = url.split("&").reduce((acc, pair) => {
const [key, value] = pair.split("=");
acc[key] = value;
return acc;
}, {});
console.log(params); // { name: "东巴文", age: "1" }
// 解析CSV
const csv = "东巴文,1,北京";
const [name, age, city] = csv.split(",");
const str = "东巴文学习东巴文";
// 替换第一个匹配
console.log(str.replace("东巴文", "JavaScript")); // "JavaScript学习东巴文"
// 使用正则表达式全局替换
console.log(str.replace(/东巴文/g, "JavaScript")); // "JavaScript学习JavaScript"
// 使用回调函数
const result = str.replace(/东巴文/g, (match, offset) => {
return `[${match}]`;
});
console.log(result); // "[东巴文]学习[东巴文]"
const str = "东巴文学习东巴文";
// 替换所有匹配
console.log(str.replaceAll("东巴文", "JavaScript")); // "JavaScript学习JavaScript"
// 使用正则表达式(需要全局标志)
console.log(str.replaceAll(/东巴文/g, "JS"));
| 方法 | 替换范围 | 东巴文建议 |
|---|---|---|
| replace | 第一个 | 单次替换 |
| replaceAll | 全部 | 全部替换 |
const str = "Hello 东巴文";
// 转大写
console.log(str.toUpperCase()); // "HELLO 东巴文"
// 转小写
console.log(str.toLowerCase()); // "hello 东巴文"
const str = "ISTANBUL";
// 考虑地区规则
console.log(str.toLocaleLowerCase("tr-TR")); // "istanbul"(土耳其语规则)
console.log(str.toLowerCase()); // "istanbul"
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log(capitalize("hello")); // "Hello"
// 每个单词首字母大写
function titleCase(str) {
return str.split(" ")
.map(word => capitalize(word))
.join(" ");
}
console.log(titleCase("hello world")); // "Hello World"
const str1 = "东巴";
const str2 = "文";
console.log(str1.concat(str2)); // "东巴文"
console.log(str1.concat("文", "学习")); // "东巴文学习"
const name = "东巴文";
const greeting = "你好," + name + "!";
console.log(greeting); // "你好,东巴文!"
const name = "东巴文";
const age = 1;
// 模板字符串(推荐)
const message = `你好,${name}!你今年${age}岁。`;
console.log(message); // "你好,东巴文!你今年1岁。"
// 多行字符串
const html = `
<div>
<h1>${name}</h1>
<p>年龄:${age}</p>
</div>
`;
const str = " 东巴文 ";
// 去除两端空白
console.log(str.trim()); // "东巴文"
console.log(str.trimStart()); // "东巴文 "
console.log(str.trimEnd()); // " 东巴文"
// 别名
console.log(str.trimLeft()); // "东巴文 "
console.log(str.trimRight()); // " 东巴文"
function trimChars(str, chars) {
const regex = new RegExp(`^[${chars}]+|[${chars}]+$`, "g");
return str.replace(regex, "");
}
console.log(trimChars("---东巴文---", "-")); // "东巴文"
console.log(trimChars("xxx东巴文xxx", "x")); // "东巴文"
const str = "5";
// 在前面填充
console.log(str.padStart(3, "0")); // "005"
console.log(str.padStart(5, "0")); // "00005"
// 默认填充空格
console.log(str.padStart(5)); // " 5"
const str = "5";
// 在后面填充
console.log(str.padEnd(3, "0")); // "500"
console.log(str.padEnd(5, "0")); // "50000"
// 格式化数字
function formatNumber(num, length = 2) {
return String(num).padStart(length, "0");
}
console.log(formatNumber(5)); // "05"
console.log(formatNumber(12)); // "12"
console.log(formatNumber(5, 4)); // "0005"
// 格式化时间
function formatTime(date) {
const h = String(date.getHours()).padStart(2, "0");
const m = String(date.getMinutes()).padStart(2, "0");
const s = String(date.getSeconds()).padStart(2, "0");
return `${h}:${m}:${s}`;
}
const str = "东巴文";
console.log(str.repeat(3)); // "东巴文东巴文东巴文"
console.log(str.repeat(0)); // ""
// 小数会取整
console.log(str.repeat(2.5)); // "东巴文东巴文"
// 负数或Infinity会报错
// str.repeat(-1); // RangeError
// 创建分隔线
const separator = "-".repeat(20);
console.log(separator); // "--------------------"
// 创建缩进
function indent(str, spaces = 4) {
const prefix = " ".repeat(spaces);
return str.split("\n").map(line => prefix + line).join("\n");
}
const str = "东巴文";
for (const char of str) {
console.log(char);
}
// 东
// 巴
// 文
const str = "东巴文";
const chars = [...str];
console.log(chars); // ["东", "巴", "文"]
const str = "东巴文";
const iterator = str[Symbol.iterator]();
console.log(iterator.next()); // { value: "东", done: false }
console.log(iterator.next()); // { value: "巴", done: false }
console.log(iterator.next()); // { value: "文", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
掌握了字符串方法后,让我们继续学习:
东巴文(db-w.cn) - 让编程学习更简单
📝 东巴文寄语:字符串是JavaScript中最常用的数据类型之一,掌握字符串的各种操作方法,能让你高效地处理文本数据。在 db-w.cn,我们帮你精通字符串操作!