JavaScript中的字符串是一种基本的数据类型,用于表示文本。字符串可以由单引号 (')、双引号 (“”) 或反引号(``)包围的字符序列组成。
创建字符串
- 单引号:
let str1 = 'Hello, World!';
- 双引号:
let str2 = "Hello, World!";
- 反引号:
let str3 =
Hello, World!;
(反引号允许字符串中包含换行符和变量)
字符串连接
使用加号 (+
) 操作符可以将两个或多个字符串连接起来:
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName; // John Doe
字符串模板
ES6引入了模板字符串,使用反引号和 ${}
表达式来嵌入变量或表达式:
let name = 'Alice';
let greeting = `Hello, ${
name}!`; // Hello, Alice!
获取字符串长度
使用 length
属性可以获取字符串的长度:
let str = 'Hello, World!';
console.log(str.length