学习JavaScript:使用字符串

Strings are the second most common data type used in JavaScript, and in many cases, since JavaScript is so widely used for web applications, it is the prominent data type. In this article I’ll discuss how strings work in JavaScript and how to work with them efficiently and effectively. I’ll also discuss some newer abilities of strings that are just being discovered and used.

字符串是JavaScript中使用的第二常见数据类型,并且在许多情况下,由于JavaScript广泛用于Web应用程序,因此它是突出的数据类型。 在本文中,我将讨论字符串如何在JavaScript中工作以及如何有效地使用它们。 我还将讨论刚刚发现和使用的字符串的一些较新功能。

定义的字符串 (Strings Defined)

A string is any set of 0 or more characters enclosed in either single quotes or double quotes. The characters in a string can be alphabetic characters, numbers, symbols, and spaces. Here are some examples of JavaScript string literals:

字符串是用单引号或双引号引起的0或多个字符的任何集合。 字符串中的字符可以是字母,数字,符号和空格。 以下是一些JavaScript字符串文字的示例:

"hello world"
'good bye, world!'
"1600 Pennsylvania Avenue"
'$*&!@ it!'

If you are using single quotes in your string, and you need to embed a single quote to write out a contraction, you use the backslash character (\) as an escape character. To see why you need to do this, let’s look at what happens when you don’t escape a single quote by writing out such a string in the JavaScript shell:

如果在字符串中使用单引号,并且需要嵌入单引号以写出收缩,则可以将反斜杠字符( \ )用作转义字符。 为了了解为什么需要这样做,让我们看一下在JavaScript外壳中写出这样的字符串时,如果不转义单引号,会发生什么情况:

js> 'can't'
typein:1:5 SyntaxError: unexpected token: identifier:
typein:1:5 'can't'
typein:1:5 .....^

The interpreter can’t figure out what to do with the ‘t’ after the single quote.

解释器无法弄清楚单引号后的“ t”是什么。

Now watch what happens when we escape the single quote:

现在看看当我们转义单引号时会发生什么:

js> 'can\'t'
"can't"

The escape character tells the interpreter to treat the single quote as an apostrophe and not as an “end-of-string” character.

转义字符告诉解释器将单引号视为撇号而不是“字符串结尾”字符。

You can embed other characters into a string, including the newline character (\n) and the tab character (\t). Here are some examples using the shell:

您可以将其他字符嵌入到字符串中,包括换行符( \n )和制表符( \t )。 以下是一些使用shell的示例:

js> print("Hello, \n world!");
Hello,
world!
js> print("Hello, \tworld");
Hello, world

In case you’re wondering, you can escape these characters as well, as in this example:

如果您想知道,也可以转义这些字符,如以下示例所示:

js> print("The newline character is \\n.");
The newline character is \n.

字符串运算 (String Operations)

There is one built-in operator that works on strings — the concatenation operator (+). The concatenation operator is used to put two or more strings together to form one string. Here are some examples using the shell:

有一个内置的运算符可用于字符串-串联运算符( + )。 串联运算符用于将两个或多个字符串放在一起以形成一个字符串。 以下是一些使用shell的示例:

js> "Paul" + "McCartney"
"PaulMcCartney"
js> "John" + " " + "Lennon"
"John Lennon"
js> "John" + " Paul" + " George Ringo"
"John Paul George Ringo"

You can use single-quoted strings and double-quoted strings together when concatenating:

串联时,可以同时使用单引号字符串和双引号字符串:

js> 'now is the time' + " for all good people " + 'to come to the aid of their party'
"now is the time for all good people to come to the aid of their party"

After the concatenation operator, there are a set of functions you can use to perform operations on strings. One of the first things you may need to know about a string is how long it is. You can find this out using the length function:

在串联运算符之后,有一组函数可用于对字符串执行操作。 您可能需要了解的关于字符串的第一件事就是字符串的长度。 您可以使用length函数找出答案:

js> let words = "now is the time for all good people";
js> words.length;
35

If you want to repeat a string a set number of times you can use the repeat function:

如果要重复字符串设定的次数,可以使用repeat功能:

js> let greet = "Hello";
js> greet.repeat(5);
"HelloHelloHelloHelloHello"

You can search for a string inside a string using the includes function, which returns a Boolean result:

您可以使用includes函数在字符串中搜索字符串,该函数返回布尔值:

js> let words = "the quick brown fox jumped over the lazy dog";
js> words.includes("fox");
true

You can pull out a part of a string, called a substring, from a string using the substr function:

您可以使用substr函数从字符串中提取一部分字符串,称为子字符串:

js> let name = "James Earl Jones";
js> name.substr(6,4)
"Earl"

A similar function, substring, returns the substring between a starting point and an ending point:

类似的函数substring ,返回起点和终点之间的子字符串:

js> let name = "James Earl Jones";
js> name.substring(6,10);
"Earl"

If you need to replace parts of a string but don’t want to replace the complete string you can use the replace function. It takes two arguments — the string you want to replace and the replacement string. Here is an example:

如果您需要替换字符串的一部分,但又不想替换整个字符串,则可以使用replace函数。 它带有两个参数-您要替换的字符串和替换字符串。 这是一个例子:

js> let word = "recieve";
js> word = word.replace("ie", "ei");
"receive"

There are many, many more string functions you can use in JavaScript. For more information, here’s a link to a reference page for JavaScript string functions.

您可以在JavaScript中使用很多很多字符串函数。 有关更多信息, 是指向JavaScript字符串函数的参考页的链接。

模板文字 (Template Literals)

One of the most powerful new features of JavaScript strings are template literals. Template literals can do many things you either can’t do with regular strings or you can only do using more complex techniques.

JavaScript字符串最强大的新功能之一就是模板文字。 模板文字可以完成许多您不能使用常规字符串完成的事情,或者只能使用更复杂的技术来完成的事情。

A string is a template literal when you enclose the string in backticks (`) instead of single quotes or double quotes. For example:

当您将字符串用反引号( ` )而不是单引号或双引号引起来时,字符串是模板文字。 例如:

js> let greeting = `Hello, world!`;
js> print(greeting);
Hello, world!

In this respect, the template literal `Hello, world!` acts just like a regular string. Where template literals come into their own is for special cases and more complex uses of strings.

在这方面,模板文字`Hello, world!`行为就像常规字符串一样。 模板文字常用于特殊情况和更复杂的字符串用法。

Here is one example. There will be times when writing a JavaScript program when you want to break a string in the middle of a line and continue it on the next line, such as when the string is especially long. Normally, you have to do this by terminating the line with a backslash. Here is an example:

这是一个例子。 有时候编写JavaScript程序时,您想在一行的中间中断一个字符串,然后在下一行继续它,例如,当字符串特别长时。 通常,您必须使用反斜杠终止该行。 这是一个例子:

js> let sentence = "Now is the time for all good people \
to come to the aid of their party.";
js> sentence
"Now is the time for all good people to come to the aid of their party."

Using a template literal, you don’t need to use the backslash:

使用模板文字,您不需要使用反斜杠:

js> let sentence = `Now is the time for all good people
to come to the aid of their party.`;
js> sentence
"Now is the time for all good people \nto come to the aid of their party."

Another use of template literals is for substituting data into a string. Before the current versions of JavaScript, if you wanted to place variable data in a string, you had to concatenate the strings with the variable, such as in this example:

模板文字的另一种用途是将数据替换为字符串。 在当前版本JavaScript之前,如果要在字符串中放置变量数据,则必须将字符串与变量连接起来,例如以下示例:

js> let salary = 25000;
js> print("This year, your salary of $" + salary + " is going to increase by 10%.");
This year, your salary of $25000 is going to increase by 10%.

With template literals, you can put a variable directly into a string using a special syntax. Here’s how that works using the example above:

使用模板文字,您可以使用特殊语法将变量直接放入字符串中。 这是使用上面的示例的工作方式:

js> let salary = 25000;
js> print(`This year, your salary of $${salary} is going to increase by 10%.`);
This year, your salary of $25000 is going to increase by 10%.

The special syntax is the ${variable-name}. With the whole string written as a template literal, placing a variable inside ${} will tell the interpreter to replace the variable name with the value the variable is storing. This use of template literals is quite powerful and makes string programming much easier.

特殊语法是$ {variable-name} 。 将整个字符串写为模板文字后,在${}放置一个变量将告诉解释器用变量存储的值替换变量名。 模板文字的这种用法非常强大,并且使字符串编程更加容易。

There are more uses of template literals, but these are the major two uses which all JavaScript programmers should start using immediately.

模板文字有更多用途,但这是所有JavaScript程序员应立即开始使用的主要两个用途。

了解字符串很重要 (Understanding Strings is Important)

String programming in JavaScript is extremely important, especially in web programming where so much data is in string form. Learning how strings work and understanding all the string functions available will make you a better and more efficient JavaScript programmer.

JavaScript中的字符串编程非常重要,尤其是在Web编程中,其中大量数据都是字符串形式的。 学习字符串的工作方式并了解所有可用的字符串函数将使您成为一个更好,更高效JavaScript程序员。

Thanks for reading and please email me with comments and suggestions.

感谢您的阅读,请给我发电子邮件以提供评论和建议。

翻译自: https://levelup.gitconnected.com/learning-javascript-working-with-strings-c5e1cba93a8a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值