处理文本 - JavaScript 中的字符串

接下来,我们将把注意力转向字符串 - 这就是编程中所谓的文本片段。在本文中,我们将介绍学习 JavaScript 时你真正应该了解的有关字符串的所有常见知识,例如创建字符串、转义字符串中的引号以及将字符串连接在一起。

¥Next, we'll turn our attention to strings — this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining strings together.

先决条件: 对 HTML 和 CSS 有基本的了解,对 JavaScript 有了解。
目标: 熟悉 JavaScript 中字符串的基础知识。

言语的力量

¥The power of words

言语对人类非常重要 - 它们是我们交流方式的重要组成部分。由于网络是一种主要基于文本的媒介,旨在让人类交流和共享信息,因此控制网络上出现的文字对我们很有用。HTML 为文本提供结构和含义,CSS 允许我们精确地设计文本样式,JavaScript 提供了许多用于操作字符串的功能。其中包括创建自定义欢迎消息和提示、在需要时显示正确的文本标签、将术语按所需顺序排序等等。

¥Words are very important to humans — they are a large part of how we communicate. Since the web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. HTML provides structure and meaning to text, CSS allows us to precisely style it, and JavaScript offers many features for manipulating strings. These include creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more.

到目前为止,我们在课程中向你展示的几乎所有程序都涉及一些字符串操作。

¥Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.

声明字符串

¥Declaring strings

乍一看,字符串的处理方式与数字类似,但当你深入研究时,你会开始看到一些显着的差异。让我们首先在 浏览器开发者控制台 中输入一些基本行来熟悉一下。

¥Strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering some basic lines into the browser developer console to familiarize ourselves.

首先,输入以下行:

¥To start with, enter the following lines:

js
const string = "The revolution will not be televised.";
console.log(string);

就像我们对数字所做的那样,我们声明一个变量,用字符串值初始化它,然后返回该值。这里唯一的区别是,在编写字符串时,需要用引号将值引起来。

¥Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.

如果你不这样做,或者遗漏了其中一个引号,你将收到错误消息。尝试输入以下行:

¥If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:

js
const badString1 = This is a test;
const badString2 = 'This is a test;
const badString3 = This is a test';

这些行不起作用,因为任何没有引号的文本都会被解释为变量名称、属性名称、保留字或类似名称。如果浏览器无法识别未加引号的文本,则会出现错误(例如 "丢失的;声明之前")。如果浏览器可以检测到字符串的开始位置但无法检测到其结尾(由于缺少第二个引号),则会报告 "未终止的字符串文字" 错误。如果你的程序引发此类错误,请返回并检查所有字符串以确保没有丢失引号。

¥These lines don't work because any text without quotes around it is interpreted as a variable name, property name, reserved word, or similar. If the browser doesn't recognize the unquoted text, then an error is raised (e.g., "missing; before statement"). If the browser can detect where a string starts but not its end (owing to the missing second quote), it reports an "unterminated string literal" error. If your program is raising such errors, then go back and check all your strings to make sure you have no missing quotation marks.

如果你之前定义了变量 string,则以下内容将起作用 - 现在尝试一下:

¥The following will work if you previously defined the variable string — try it now:

js
const badString = string;
console.log(badString);

badString 现在设置为与 string 具有相同的值。

¥badString is now set to have the same value as string.

单引号、双引号和反引号

¥Single quotes, double quotes, and backticks

在 JavaScript 中,你可以选择单引号 (')、双引号 (") 或反引号 (```) 来包裹字符串。以下所有内容都将起作用:

¥In JavaScript, you can choose single quotes ('), double quotes ("), or backticks (`) to wrap your strings in. All of the following will work:

js
const single = 'Single quotes';
const double = "Double quotes";
const backtick = `Backtick`;

console.log(single);
console.log(double);
console.log(backtick);

字符串的开头和结尾必须使用相同的字符,否则会出现错误:

¥You must use the same character for the start and end of a string, or you will get an error:

js
const badQuotes = 'This is not allowed!";

使用单引号声明的字符串和使用双引号声明的字符串是相同的,你使用哪种样式取决于个人喜好 - 尽管选择一种样式并在代码中一致使用它是一种很好的做法。

¥Strings declared using single quotes and strings declared using double quotes are the same, and which you use is down to personal preference — although it is good practice to choose one style and use it consistently in your code.

使用反引号声明的字符串是一种特殊的字符串,称为 模板文字。在大多数情况下,模板文字与普通字符串类似,但它们具有一些特殊属性:

¥Strings declared using backticks are a special kind of string called a template literal. In most ways, template literals are like normal strings, but they have some special properties:

嵌入 JavaScript

¥Embedding JavaScript

在模板文字中,你可以将 JavaScript 变量或表达式封装在 ${ } 内,结果将包含在字符串中:

¥Inside a template literal, you can wrap JavaScript variables or expressions inside ${ }, and the result will be included in the string:

js
const name = "Chris";
const greeting = `Hello, ${name}`;
console.log(greeting); // "Hello, Chris"

你可以使用相同的技术将两个变量连接在一起:

¥You can use the same technique to join together two variables:

js
const one = "Hello, ";
const two = "how are you?";
const joined = `${one}${two}`;
console.log(joined); // "Hello, how are you?"

像这样将字符串连接在一起称为串联。

¥Joining strings together like this is called concatenation.

上下文中的串联

¥Concatenation in context

让我们看一下实际使用的串联:

¥Let's have a look at concatenation being used in action:

html
<button>Press me</button>
<div id="greeting"></div>
js
const button = document.querySelector("button");

function greet() {
  const name = prompt("What is your name?");
  const greeting = document.querySelector("#greeting");
  greeting.textContent = `Hello ${name}, nice to see you!`;
}

button.addEventListener("click", greet);

在这里,我们使用 window.prompt() 函数,它提示用户通过弹出对话框回答问题,然后将他们输入的文本存储在给定变量中 - 在本例中为 name。然后,我们显示一个字符串,将名称插入到通用问候消息中。

¥Here, we are using the window.prompt() function, which prompts the user to answer a question via a popup dialog box and then stores the text they enter inside a given variable — in this case name. We then display a string that inserts the name into a generic greeting message.

使用 "*" 连接

¥Concatenation using "+"

你只能将 ${} 与模板文字一起使用,而不能与普通字符串一起使用。你可以使用 + 运算符连接普通字符串:

¥You can use ${} only with template literals, not normal strings. You can concatenate normal strings using the + operator:

js
const greeting = "Hello";
const name = "Chris";
console.log(greeting + ", " + name); // "Hello, Chris"

但是,模板文字通常会为你提供更具可读性的代码:

¥However, template literals usually give you more readable code:

js
const greeting = "Hello";
const name = "Chris";
console.log(`${greeting}, ${name}`); // "Hello, Chris"

在字符串中包含表达式

¥Including expressions in strings

你可以在模板文字中包含 JavaScript 表达式以及变量,结果将包含在结果中:

¥You can include JavaScript expressions in template literals, as well as just variables, and the results will be included in the result:

js
const song = "Fight the Youth";
const score = 9;
const highestScore = 10;
const output = `I like the song ${song}. I gave it a score of ${
  (score / highestScore) * 100
}%.`;
console.log(output); // "I like the song Fight the Youth. I gave it a score of 90%."

多行字符串

¥Multiline strings

模板文字尊重源代码中的换行符,因此你可以编写跨多行的字符串,如下所示:

¥Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:

js
const newline = `One day you finally knew
what you had to do, and began,`;
console.log(newline);

/*
One day you finally knew
what you had to do, and began,
*/

要使用普通字符串获得等效的输出,你必须在字符串中包含换行符 (\n):

¥To have the equivalent output using a normal string you'd have to include line break characters (\n) in the string:

js
const newline = "One day you finally knew\nwhat you had to do, and began,";
console.log(newline);

/*
One day you finally knew
what you had to do, and began,
*/

有关高级功能的更多示例和详细信息,请参阅我们的 模板文字 参考页。

¥See our Template literals reference page for more examples and details of advanced features.

在字符串中包含引号

¥Including quotes in strings

既然我们使用引号来指示字符串的开头和结尾,那么如何在字符串中包含实际的引号呢?我们知道这是行不通的:

¥Since we use quotes to indicate the start and end of strings, how can we include actual quotes in strings? We know that this won't work:

js
const badQuotes = "She said "I think so!"";

一种常见的选择是使用其他字符之一来声明字符串:

¥One common option is to use one of the other characters to declare the string:

js
const goodQuotes1 = 'She said "I think so!"';
const goodQuotes2 = `She said "I'm not going in there!"`;

另一种选择是转义问题引号。转义字符意味着我们对它们进行一些操作以确保它们被识别为文本,而不是代码的一部分。在 JavaScript 中,我们通过在字符前面放置反斜杠来实现这一点。尝试这个:

¥Another option is to escape the problem quotation mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:

js
const bigmouth = 'I\'ve got no right to take my place…';
console.log(bigmouth);

你可以使用相同的技术插入其他特殊字符。详细信息请参见 转义序列

¥You can use the same technique to insert other special characters. See Escape sequences for more details.

数字与字符串

¥Numbers vs. strings

当我们尝试连接字符串和数字时会发生什么?让我们在控制台中尝试一下:

¥What happens when we try to concatenate a string and a number? Let's try it in our console:

js
const name = "Front ";
const number = 242;
console.log(name + number); // "Front 242"

你可能期望这会返回错误,但它工作得很好。数字如何显示为字符串是相当明确的,因此浏览器会自动将数字转换为字符串并将两个字符串连接起来。

¥You might expect this to return an error, but it works just fine. How numbers should be displayed as strings is fairly well-defined, so the browser automatically converts the number to a string and concatenates the two strings.

如果你有一个想要转换为字符串的数值变量或一个想要转换为数字的字符串变量,则可以使用以下两个构造:

¥If you have a numeric variable that you want to convert to a string or a string variable that you want to convert to a number, you can use the following two constructs:

  • 如果可以的话,Number() 函数会将传递给它的任何内容转换为数字。请尝试以下操作:
    js
    const myString = "123";
    const myNum = Number(myString);
    console.log(typeof myNum);
    // number
    
  • 相反,String() 函数将其参数转换为字符串。尝试这个:
    js
    const myNum2 = 123;
    const myString2 = String(myNum2);
    console.log(typeof myString2);
    // string
    

这些结构在某些情况下非常有用。例如,如果用户在表单的文本字段中输入数字,则它是一个字符串。但是,如果你想将此数字添加到某些内容中,则需要它是一个数字,因此你可以通过 Number() 传递它来处理此问题。我们在 猜数字游戏 中的 checkGuess 函数中正是这样做的。

¥These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through Number() to handle this. We did exactly this in our Number Guessing Game, in the checkGuess function.

结论

¥Conclusion

这就是 JavaScript 中涉及的字符串的基础知识。在下一篇文章中,我们将以此为基础,研究 JavaScript 中字符串可用的一些内置方法,以及如何使用它们将字符串操作为我们想要的形式。

¥So that's the very basics of strings covered in JavaScript. In the next article, we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.