犀牛书第七版学习笔记:数据类型与结构-字符串

本文详细探讨了JavaScript中的字符串,包括字符串的16位值性质、字符串字面量、转义序列、字符串处理(如连接和比较)、模板字面量以及模式匹配。特别是字符串的不可变性,以及如何通过模板字面量和标记模板字面量进行字符串操作。此外,还介绍了正则表达式在匹配文本模式中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

0.字符串与16位值

1.字符串字面量

2.字符串字面量中的转义序列Escape Sequences in String Literals

3.处理字符串Working with Strings

1.连接

2.比较

3.字符串的长度与其他api

4.模板字面量Template Literals

1.标记的模板字面量TAGGED TEMPLATE LITERALS

5.模式匹配Pattern Matching


0.字符串与16位值

字符串是16位值的不可变有序序列,每个值通常代表一个Unicode字符。A string is an immutable ordered sequence of 16-bit values, each of which typically represents a Unicode character

字符串的长度是它包含的16位值的数量。The length of a string is the number of 16-bit values it contains

JavaScript的字符串(及其数组)使用基于零的索引:第一个16位的值在位置0,第二个在位置1,依此类推。

空字符串是长度为0的字符串。

JavaScript没有一种特殊的类型来表示字符串中的单个元素a single element of a string。要表示单个16位值,只需使用长度为1的字符串

  • sequences of Unicode characters
  • sequences of UTF-16 code units (each code unit is represented by a 16-bit number)
  • Each Unicode character is represented by either 1 or 2 code units.

unicode character ⇒ code unit编码单元 ⇒ 16-bit number 16 位二进制数

'hello'.length; // 5 字符串的 length(编码单元的个数)

字符character、代码点codepoint和 JAVASCRIPT 字符串

JavaScript 使用 Unicode 字符集的 UTF-16 编码,JavaScript 字符串是无符号 16 位值的序列。

最常用的 Unicode 字符具有适合 16 位的代码点,并且可以由字符串的一个元素表示。

代码点不适合 16 位的 Unicode 字符被编码为两个 16 位值的序列(称为“代理对surrogate pair”)。这意味着长度为 2 的 JavaScript 字符串(两个 16 位值)可能只表示单个 Unicode 字符

let euro = "€"; 
let love = "❤"; 
euro.length // => 1: this character has one 16-bit element 
love.length // => 2: UTF-16 encoding of ❤ is "\\ud83d\\udc99"

var p = "π"; // π is 1 character with 16-bit codepoint 0x03c0
var e = "e"; // e is 1 **character with 17-bit codepoint 0x1d452**
p.length     // => 1: p consists of 1 16-bit element
e.length     // => 2: UTF-16 encoding of e is 2 16-bit values: "\\ud835\\udc52"

JavaScript 定义的大多数字符串操作方法都对 16 位值进行操作,而不是字符。它们不特别对待代理对,它们不执行字符串的规范化normalization of the string,甚至不确保字符串是格式正确的 UTF-16。

在 ES6 中,字符串是可迭代的,如果你对字符串使用 for/of 循环或 ... 运算符,它将迭代字符串的实际字符,而不是 16 位值

像  object 一样使用字符串

字符串也有 methods(方法)能让你操作字符串和获取字符串的信息

"hello".charAt(0); // "h"
"hello, world".replace("world", "mars"); // "hello, mars"
"hello".toUpperCase(); // "HELLO"

1.字符串字面量

"" // The empty string: it has zero characters 
'testing' 
"3.14" 
'name="myform"' 
"Wouldn't you prefer O'Reilly's book?" 
"τ is the ratio of a circle's circumference to its radius" 
`"She said 'hi'", he said.`

当使用单引号分隔字符串时,必须注意英文缩写和所有格,例如can 't和O 'Reilly。\

由于撇号apostrophe与单引号字符相同,您必须使用反斜杠字符(\)来“转义”“escape”出现在单引号字符串中的任何撇号

2.字符串字面量中的转义序列Escape Sequences in String Literals

反斜杠字符(\)在JavaScript字符串中有一个特殊的用途。它与其后的字符组合,表示在字符串中用其他方式就无法表示的字符。it represents a character that is not otherwise representable within the string

\n是表示换行符的转义序列escape sequence

\'表示单引号(或撇号)字符。即在包含在单引号中的字符串字面量中包含撇号

反斜杠允许您转义单引号字符的通常解释escape from the usual interpretation of the single-quote character。不使用它来标记字符串的结束,而是将它用作撇号

'You\\'re right, it can\\'t be a quote'

3.处理字符串Working with Strings

1.连接

JavaScript的内置特性之一是连接字符串concatenate strings的能力。

如果你对数字使用+运算符,它会将它们相加。但如果你对字符串使用这个操作符,它通过将第二个加到第一个上来连接它们 it joins them by appending the second to the first

let msg = "Hello, " + "world"; // Produces the string "Hello, world" 
let greeting = "Welcome to my blog," + " " + name;

2.比较

字符串可以用标准的===相等和!==不等操作符进行比较:两个字符串当且仅当它们包含完全相同的16位值序列时是相等的。

字符串还可以使用<、<=、>和>=操作符进行比较。字符串比较只需比较16位值即可。

3.字符串的长度与其他api

要确定字符串的长度(它包含的16位值的数量),请使用字符串的length属性

s.length

JavaScript为处理字符串提供了丰富的API

let s = "Hello, world"; // Start with some text. 

// Obtaining portions of a string 
s.substring(1,4) // => "ell": the 2nd, 3rd, and 4th characters. 
s.slice(1,4) // => "ell": same thing 
s.slice(-3) // => "rld": last 3 characters 
s.split(", ") // => ["Hello", "world"]: split at delimiter string 

// Searching a string 
s.indexOf("l") // => 2: position of first letter l 
s.indexOf("l", 3) // => 3: position of first "l" at or after 3 
s.indexOf("zz") // => -1: s does not include the substring "zz" 
s.lastIndexOf("l") // => 10: position of last letter l 

// Boolean searching functions in ES6 and later 
s.startsWith("Hell") // => true: the string starts with these 
s.endsWith("!") // => false: s does not end with that 
s.includes("or") // => true: s includes substring "or" 

// Creating modified versions of a string 
s.replace("llo", "ya") // => "Heya, world" 
s.toLowerCase() // => "hello, world" 
s.toUpperCase() // => "HELLO, WORLD" 
s.normalize() // Unicode NFC normalization: ES6 
s.normalize("NFD") // NFD normalization. Also "NFKC", "NFKD" 

// Inspecting individual (16-bit) characters of a string 
s.charAt(0) // => "H": the first character 
s.charAt(s.length-1) // => "d": the last character 
s.charCodeAt(0) // => 72: 16-bit number at the specified position 
s.codePointAt(0) // => 72: ES6, works for codepoints >16 bits

// String padding functions in ES2017 
"x".padStart(3) // => " x": add spaces on the left to a length of 3 
"x".padEnd(3) // => "x ": add spaces on the right to a length of 3 
"x".padStart(3, "*") // => "**x": add stars on the left to a length of 3 
"x".padEnd(3, "-") // => "x--": add dashes on the right to a length of 3 

// Space trimming functions. trim() is ES5; others ES2019 
" test ".trim() // => "test": remove spaces at start and end 
" test ".trimStart() // => "test ": remove spaces on left. Also trimLeft 
" test ".trimEnd() // => " test": remove spaces at right. Also trimRight 

// Miscellaneous string methods 
s.concat("!") // => "Hello, world!": just use + operator instead 
"<>".repeat(5) // => "<><><><><>": concatenate n copies. ES6

记住,字符串在JavaScript中是不可变immutable的。像replace()和toUpperCase()这样的方法返回新的字符串:它们不会修改调用它们的字符串。they do not modify the string on which they are invoked

字符串也可以像只读数组read-only arrays一样处理,可以使用方括号而不是charAt()方法从字符串中访问单个字符(16位值)access individual characters (16-bit values) from a string

let s = "hello, world"; 
s[0] // => "h" 
s[s.length-1] // => "d"

4.模板字面量Template Literals

模板字面量可以包括任意JavaScript表达式。arbitrary JavaScript expressions

撇号中的字符串字面值的最终值是通过计算任何包含的表达式来计算的,将这些表达式的值转换为字符串,并将这些计算出来的字符串与撇号中的字面值字符结合起来

let name = "Bill"; 
let greeting = `Hello ${ name }.`; 
// greeting == "Hello Bill."

模板字面量可以包含任意数量的表达式。它可以使用普通字符串可以使用的任何转义字符,并且不需要特殊的转义就可以跨越任意数量的行,。

下面的模板字面量包括四个JavaScript表达式、一个Unicode转义序列和至少四个新行(表达式值也可以包含换行符)

let errorMessage = `\\ 
 \\u2718 Test failure at ${filename}:${linenumber}:
 ${exception.message}
Stack trace: 
${exception.stack} 
`;

//这里第一行末尾的反斜杠转义了初始换行符,因此结果字符串以Unicode的✘字符(\\u2718)开始,而不是以换行符开始

1.标记的模板字面量TAGGED TEMPLATE LITERALS

如果函数名(或“标记”)恰好出现在开头的反撇号之前,那么模板字面量中的文本和表达式的值将传递给该函数。这个“标记模板字面量”的值是函数的返回值。if a function name (or “tag”) comes right before the opening backtick, then the text and the values of the expressions within the template literal are passed to the function. The value of this “tagged template literal” is the return value of the function

例如,这可以用于在将值替换为文本之前对它们(值)应用HTML或SQL转义。to apply HTML or SQL escaping to the values before substituting them into the text

ES6有一个内置的标记函数:String.raw()。它返回反引号内的文本,不处理任何反斜杠转义 It returns the text within backticks without any processing of backslash escapes

`\\n`.length // => 1: the string has a single newline character 该字符串只有一个换行符
String.raw`\\n`.length // => 2: a backslash character and the letter n 一个反斜杠字符和字母n

//即使已标记模板字面量的标记部分是一个函数,在其调用中也没有使用圆括号。在这个非常具体的例子中,撇号取代了左括号和右括号
//even though the tag portion of a tagged template literal is a function, there are no parentheses used in its invocation. In this very specific case, the backtick characters replace the open and close parentheses

定义自己的模板标记函数template tag functions是JavaScript的一个强大特性。

这些函数不需要返回字符串,它们可以像构造函数constructors一样使用,就像为语言定义新的字面量语法defining a new literal syntax for the language一样

5.模式匹配Pattern Matching

JavaScript定义了一种被称为正则表达式regular expression(或RegExp)的数据类型,用于描述和匹配matching文本字符串中的模式patterns。

regexp不是JavaScript中的基本数据类型之一,但它们像数字和字符串一样具有文字语法literal syntax,所以它们有时看起来像是基本的。

正则表达式字面量的语法很复杂,它们定义的API也很重要。

一对斜杠之间的文本构成一个正则表达式字面量。这对斜杠中的第二个斜杠的后面也可以跟着一个或多个字母,用于修改模式的含义modify the meaning of the pattern

/^HTML/; // Match the letters H T M L at the start of a string 匹配字符串开头的字母H T M L
/[1-9][0-9]*/; // Match a nonzero digit, followed by any # of digits 
/\\bjavascript\\b/i; // Match "javascript" as a word, case- insensitive

RegExp对象objects定义了许多有用的方法methods,字符串也有接受RegExp参数RegExp arguments的方法

let text = "testing: 1, 2, 3"; // Sample text 
let pattern = /\d+/g; // Matches all instances of one or more digits 匹配一个或多个数字的所有实例
pattern.test(text) // => true: a match exists 
text.search(pattern) // => 9: position of first match 
text.match(pattern) // => ["1", "2", "3"]: array of all matches 
text.replace(pattern, "#") // => "testing: #, #, #" 
text.split(/\D+/) // => ["","1","2","3"]: split on nondigits

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值