Skip to content

JavaScript字符串常用方法总结 ​

1. 字符串访问方法 ​

这些方法用于访问字符串中的单个字符:

js
const str = "hello world";

// 获取指定位置的字符
str.charAt(1)      // 返回: 'e'
str.charCodeAt(1)  // 返回: 101 (字符'e'的Unicode值)
str[1]            // 返回: 'e' (IE8+支持)

2. 字符串查找方法 ​

用于在字符串中查找子串:

js
const str = "hello world";

// 查找子串位置
str.indexOf('o')      // 返回第一个'o'的位置: 4
str.lastIndexOf('o')  // 返回最后一个'o'的位置: 7

// ES6新增的查找方法
str.includes('hello')     // 返回: true
str.startsWith('hello')   // 返回: true
str.endsWith('world')     // 返回: true

3. 字符串操作方法 ​

截取方法

js
const str = "hello world";

// 查找子串位置
str.indexOf('o')      // 返回第一个'o'的位置: 4
str.lastIndexOf('o')  // 返回最后一个'o'的位置: 7

// ES6新增的查找方法
str.includes('hello')     // 返回: true
str.startsWith('hello')   // 返回: true
str.endsWith('world')     // 返回: true

转换方法

js
const str = "Hello World";

// 大小写转换
str.toLowerCase()         // "hello world"
str.toUpperCase()         // "HELLO WORLD"
str.toLocaleLowerCase()   // "hello world"
str.toLocaleUpperCase()   // "HELLO WORLD"

字符串处理方法

js
// 分割字符串
"a,b,c".split(',')    // 返回: ['a', 'b', 'c']

// 去除空白
" hello ".trim()      // 返回: "hello"

// 重复字符串
"ha".repeat(3)        // 返回: "hahaha"

// 连接字符串
"hello".concat(" ", "world")  // 返回: "hello world"

4. 字符串模式匹配 ​

js
const str = "hello world";

// 替换
str.replace('world', 'javascript')  // 返回: "hello javascript"

// 使用正则替换
str.replace(/o/g, '0')             // 返回: "hell0 w0rld"

// 查找匹配
str.match(/o/g)       // 返回: ['o', 'o']
str.search(/world/)   // 返回: 6

5. 字符串转换方法 ​

js
// 字符串转数字
parseInt("123")       // 返回: 123
parseFloat("123.45")  // 返回: 123.45

// 进制转换
parseInt("1010", 2)   // 返回: 10 (二进制转十进制)

6. 字符串比较 ​

js
// 字符串比较
'a'.localeCompare('b')   // 返回负数
'b'.localeCompare('a')   // 返回正数
'a'.localeCompare('a')   // 返回0

注意事项 ​

  1. 大多数字符串方法都不会修改原字符串,而是返回新的字符串

  2. slice()、substring()和substr()的主要区别在于参数的含义和负值的处理方式

  3. 使用replace()进行全局替换时,需要使用正则表达式的g标志

  4. ES6新增了很多实用的字符串方法(如includes()、startsWith()、endsWith()、repeat()等)