JavaScript 字符串常用的方法

63 阅读2分钟

1. 字符串查找

  • indexOf():返回指定字符串在原字符串中第一次出现的位置,如果没有找到则返回 -1。
const str = 'Hello, World!';
console.log(str.indexOf('o')); // 输出 4
  • lastIndexOf():返回指定字符串在原字符串中最后一次出现的位置,如果没有找到则返回 -1。
const str = 'Hello, World!';
console.log(str.lastIndexOf('l')); // 输出 10
  • includes():如果原字符串包含指定字符串,返回 true,否则返回 false。
const str = 'Hello, World!';
console.log(str.includes('World')); // 输出 true
  • charAt():返回指定位置的字符。
const str = 'Hello, World!';
console.log(str.charAt(0)); // 输出 H
console.log(str.charAt(100)); // 输出 undefined

2. 字符串截取

  • slice():从原字符串中提取一个子字符串并返回,不会修改原字符串。
const str = 'Hello, World!';
console.log(str.slice(0, 5)); // 输出 Hello
  • substring():从原字符串中提取一个子字符串并返回,不会修改原字符串。
const str = 'Hello, World!';
console.log(str.substring(7, 12)); // 输出 World
  • substr():从原字符串中提取一个子字符串并返回,不会修改原字符串。
const str = 'Hello, World!';
console.log(str.substr(7, 5)); // 输出 World

3. 字符串替换

  • replace():将指定的子字符串替换成另一个字符串,并返回新的字符串。
const str = 'Hello, World!';
console.log(str.replace('World', 'JavaScript')); // 输出 Hello, JavaScript!

4. 字符串分割

  • join():将数组中的所有元素合并为一个字符串。
const arr = ['Hello', 'World'];
console.log(arr.join(', ')); // 输出 "Hello, World"
  • split():将原字符串分割成多个子字符串,并返回一个数组。
const str = 'Hello, World!';
console.log(str.split(',')); // 输出 ['Hello', ' World!']

5. 字符串大小写转换

  • toUpperCase():将原字符串中的所有字母转换为大写字母,并返回新的字符串。
const str = 'Hello, World!';
console.log(str.toUpperCase()); // 输出 HELLO, WORLD!
  • toLowerCase():将原字符串中的所有字母转换为小写字母,并返回新的字符串。
const str = 'Hello, World!';
console.log(str.toLowerCase()); // 输出 hello, world!

6. 编码解码

  • encodeURI():对 URI 进行编码。
const uri = 'http://example.com/?a=你好&b=world';
console.log(encodeURI(uri)); // 输出 http://example.com/?a=%E4%BD%A0%E5%A5%BD&b=world
  • decodeURI():将编码后的 URI 进行解码。
const uri = 'http://example.com/?a=%E4%BD%A0%E5%A5%BD&b=world';
console.log(decodeURI(uri)); // 输出 http://example.com/?a=你好&b=world

7. 字符串转义

  • escape():对字符串进行编码,将非 ASCII 字符转换成十六进制编码。
const str = '<html>hello world</html>';
console.log(escape(str)); // 输出 %3Chtml%3Ehello%20world%3C/html%3E
  • unescape():将 escape() 编码后的字符串进行解码还原回来。
const str = '%3Chtml%3Ehello%20world%3C/html%3E';
console.log(unescape(str)); // 输出 <html>hello world</html>

8. 其他方法

  • trim():去掉字符串两端的空格,并返回新的字符串。
const str = '   Hello, World!   ';
console.log(str.trim()); // 输出 Hello, World!