JavaScript 内置对象-字符串对象

91 阅读3分钟

在JavaScript中,字符串(String)是处理文本数据的基础类型之一。虽然从技术上讲,字符串不是真正的对象,但JavaScript提供了丰富的内置方法来操作字符串,使得它几乎像一个拥有众多实用功能的对象。本文将详细介绍如何使用这些方法来处理和操作字符串。

一、创建字符串

使用字面量

最直接的方式是通过字符串字面量创建一个字符串:

let str = "Hello, World!";
console.log(str); // 输出: Hello, World!

注意:单引号 ' 和双引号 " 都可以用来定义字符串,但在同一个字符串内部应保持一致。

使用构造函数

也可以使用 String 构造函数来创建字符串对象:

let strObj = new String("Hello, World!");
console.log(strObj); // 输出: String {"Hello, World!"}

然而,在大多数情况下,建议使用字面量而非构造函数,因为前者更简洁且性能更好。

二、常用字符串方法

获取字符

  • charAt(index) :返回指定位置的字符。
  • charCodeAt(index) :返回指定位置字符的Unicode编码值。
let str = "Hello";
console.log(str.charAt(1)); // 输出: e
console.log(str.charCodeAt(1)); // 输出: 101

查找子串

  • indexOf(searchValue[, fromIndex]) :返回searchValue首次出现的位置;如果未找到则返回-1。
  • lastIndexOf(searchValue[, fromIndex]) :类似indexOf,但从右向左查找。
let sentence = "Learning JavaScript is fun.";
console.log(sentence.indexOf("JavaScript")); // 输出: 9
console.log(sentence.lastIndexOf("is")); // 输出: 20

提取子串

  • substring(start[, end]) :提取start到end(不包括end)之间的字符。
  • slice(start[, end]) :与substring类似,但支持负数索引,表示从字符串末尾开始计算的位置。
  • substr(start[, length]) :从start位置开始提取长度为length的子串。
let text = "The quick brown fox jumps over the lazy dog.";
console.log(text.substring(4, 9)); // 输出: quick
console.log(text.slice(-4)); // 输出: dog.
console.log(text.substr(4, 5)); // 输出: quick

替换与修改

  • replace(searchValue, newValue) :用newValue替换第一个匹配searchValue的子串。支持正则表达式作为searchValue。
  • replaceAll(searchValue, newValue) :用newValue替换所有匹配searchValue的子串(ES2021新增)。
let oldStr = "I love cats and cats.";
console.log(oldStr.replace("cats", "dogs")); // 输出: I love dogs and cats.
console.log(oldStr.replaceAll("cats", "dogs")); // 输出: I love dogs and dogs.

大小写转换

  • toLowerCase() :将整个字符串转为小写。
  • toUpperCase() :将整个字符串转为大写。
let mixedCase = "HeLLo WoRLD!";
console.log(mixedCase.toLowerCase()); // 输出: hello world!
console.log(mixedCase.toUpperCase()); // 输出: HELLO WORLD!

去除空白

  • trim() :移除字符串两端的空白字符。
  • trimStart() / trimLeft() :仅移除字符串开头的空白字符。
  • trimEnd() / trimRight() :仅移除字符串结尾的空白字符。
let spacey = "   Extra spaces   ";
console.log(spacey.trim()); // 输出: Extra spaces
console.log(spacey.trimStart()); // 输出: Extra spaces   
console.log(spacey.trimEnd()); // 输出:    Extra spaces

拆分与合并

  • split([separator[, limit]]) :根据separator拆分字符串为数组。
  • concat(...args) :连接两个或多个字符串并返回新字符串。
let sentence = "Split this into words.";
console.log(sentence.split(" ")); // 输出: ["Split", "this", "into", "words."]
console.log("Hello".concat(", ", "World!")); // 输出: Hello, World!

三、模板字符串

ES6引入了模板字符串(Template Literals),允许嵌入变量和表达式,大大简化了字符串拼接的工作。

let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // 输出: Hello, Alice!

模板字符串还支持多行文本而无需手动添加换行符或转义字符:

let poem = `
Roses are red,
Violets are blue,
This line breaks naturally,
Isn't that cool?
`;
console.log(poem);

四、结语

感谢您的阅读!如果您对JavaScript的字符串对象或者其他相关话题有任何疑问或见解,欢迎继续探讨。