Appearance
字符串方法
获取长度
javascript
const s = "hello world!";
console.log(s.length); // 空格也算一个字符
大小写转换
javascript
console.log(s.toUpperCase()); // 转大写
console.log(s.toLowerCase()); // 转小写
截取
javascript
console.log(s.substring(0, 5)); // "hello"
console.log(s.slice(0, 5)); // "hello"(支持负数)
console.log(s.charAt(0)); // "h"
分割与合并
javascript
console.log(s.split(" ")); // ["hello", "world!"]
const arr = ["a", "b", "c"];
console.log(arr.join("-")); // "a-b-c"
查找与替换
javascript
console.log(s.includes("hello")); // true
console.log(s.indexOf("world")); // 6
console.log(s.replace("world", "js")); // "hello js!"
去除空白
javascript
const raw = " hello ";
console.log(raw.trim()); // "hello"
console.log(raw.trimStart()); // "hello "
console.log(raw.trimEnd()); // " hello"
模板字符串
使用反引号(`)包裹字符串,用 ${} 来嵌入变量或表达式:
javascript
const name = "ty";
const age = 21;
console.log(`my name is ${name} and age is ${age}`);
相比传统的字符串拼接,模板字符串更简洁、可读性更强。