Javascript 简明教程

JavaScript - Strings

JavaScript 中的 String 对象允许您处理一系列字符;它用多个帮助程序方法包装 JavaScript 的字符串基础数据类型。

The String object in JavaScript lets you work with a series of characters; it wraps JavaScript’s string primitive data type with a number of helper methods.

由于 JavaScript 会在字符串基元和 String 对象之间自动转换,因此您可以在字符串基元上调用 String 对象的任何辅助方法。

As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.

字符串是包含 0 个或更多个字符的字符序列。例如,'Hello' 是一个字符串。

The string is a sequence of characters containing 0 or more characters. For example, 'Hello' is a string.

Syntax

可以使用 String() 构造函数将 JavaScript 字符串作为对象创建,或者使用字符串字面量作为基本类型创建。

JavaScript strings can be created as objects using the String() constructor or as primitives using string literals.

使用以下语法创建 String 对象 −

Use the following syntax to create a String object −

var val = new String(value);

String 参数(值)是一系列已正确编码的字符。

The String parameter, value is a series of characters that has been properly encoded.

我们可以使用字符串文字和 String() 函数(如下所示)来创建字符串基元 -

We can create string primitives using string literals and the String() function as follows −

str1 = 'Hello World!'; // using single quote
str2 = "Hello World!"; // using double quote
str3 = 'Hello World'; // using back ticks
str4 = String('Hello World!'); // using String() function

JavaScript String Object Properties

以下是 String 对象的属性及其说明的列表。

Here is a list of the properties of String object and their description.

Sr.No.

Property

Description

1

constructor

Returns a reference to the String function that created the object.

2

length

Returns the length of the string.

3

prototype

The prototype property allows you to add properties and methods to an object.

JavaScript String Object Methods

以下是 String 对象中可用的方法及其说明的列表。

Here is a list of the methods available in String object along with their description.

Static Methods

使用“String”类本身调用静态方法。

The static methods are invoked using the 'String' class itself.

Sr.No.

Property

Description

1

fromCharCode()

Converts the sequence of UTF-16 code units into the string.

2

fromCodePoint()

Creates a string from the given sequence of ASCII values.

Instance Methods

使用 String 类的实例调用实例方法。

The instance methods are invoked using the instance of the String class.

Sr.No.

Method

Description

1

at()

Returns the character from the specified index.

2

charAt()

Returns the character at the specified index.

3

charCodeAt()

Returns a number indicating the Unicode value of the character at the given index.

4

codePointAt()

Returns a number indicating the Unicode value of the character at the given index.

5

concat()

Combines the text of two strings and returns a new string.

6

endsWith()

Checks whether the string ends with a specific character or substring.

7

includes()

To check whether one string exists in another string.

8

indexOf()

Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

9

lastIndexOf()

Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

10

localeCompare()

Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

11

match()

Used to match a regular expression against a string.

12

matchAll()

Used to match all occurrences of regular expression patterns in the string.

13

normalize()

To get the Unicode normalization of the string.

14

padEnd()

To add padding to the current string with different strings at the end.

15

padStart()

To add padding to the current string with different strings at the start.

16

raw()

Returns a raw string form of a given template literal.

17

repeat()

To get a new string containing the N number of copies of the current string.

18

replace()

Used to find a match between a regular expression and a string and replace the matched substring with a new one.

19

replaceAll()

Used to find a match between a regular expression and a string and replace all the matched substring with a new one.

20

search()

Executes the search for a match between a regular expression and a specified string.

21

slice()

Extracts a section of a string and returns a new string.

22

split()

Splits a String object into an array of strings by separating the string into substrings.

23

substr()

Returns the characters in a string beginning at the specified location through the specified number of characters.

24

substring()

Returns the characters in a string between two indexes into the string.

25

toLocaleLowerCase()

The characters within a string are converted to lowercase while respecting the current locale.

26

toLocaleUpperCase()

The characters within a string are converted to the upper case while respecting the current locale.

27

toLowerCase()

Returns the calling string value converted to lowercase.

28

toString()

Returns a string representing the specified object.

29

toUpperCase()

Returns the calling string value converted to uppercase.

30

toWellFormed()

Returns a new string that is a copy of this string.

31

trim()

It removes white spaces from both ends.

32

trimEnd()

It removes white spaces from the start.

33

trimStart()

It removes white spaces from the end.

34

valueOf()

Returns the primitive value of the specified object.

String constructor

Sr.No.

Constructor

Description

1

String()

Creates a string object and initializes it with the provided value.

Examples

让我们通过一些示例来了解 JavaScript 字符串对象和字符串基元。

Let’s take understand the JavaScript String object and string primitives with the help of some examples.

Example: Creating JavaScript String Objects

在下面的示例中,我们使用带有“new”关键字的 string() 构造函数创建了一个字符串对象。

In the example below, we used the string() constructor with the 'new' keyword to create a string object.

<html>
<head>
   <title> JavaScript - String Object </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");
      const str = new String("Hello World!");
      output.innerHTML += "str == " + str + "<br>";
      output.innerHTML += "typeof str == " + typeof str;
   </script>
</body>
</html>
str == Hello World!
typeof str == object

Accessing a string

你可以使用其索引访问字符串字符。字符串索引从 0 开始。

You can access the string characters using its index. The string index starts from 0.

在下面的示例中,我们访问了字符串第 0 个和第 4 个索引处的字符。

In the example below, we access the character from the 0th and 4th index of the string.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");
      let str1 = new String("Welcome!");
      let str2 = "Welcome!";
      output.innerHTML += "0th character is - " + str1[0] + "<br>";
      output.innerHTML += "4th character is - " + str2[4] + "<br>";
   </script>
</body>
</html>
0th character is - W
4th character is - o

JavaScript string is case-sensitive

在 JavaScript 中,字符串区分大小写。这意味着小写和大写字母不同。

In JavaScript, strings are case-sensitive. It means lowercase and uppercase characters are different.

s == S false

JavaScript Strings Are Immutable

在 JavaScript 中,你不能更改字符串的字符。但是,你可以更新整个字符串。

In JavaScript, you can’t change the characters of the string. However, you can update the whole string.

在下面的示例中,我们尝试更新字符串的第一个字符,但它并没有得到更新,你可以在输出中看到这一点。

In the example below, we try to update the first character of the string, but it doesn’t get updated, which you can see in the output.

之后,我们更新了整个字符串,你可以观察到字符串的变化。

After that, we update the whole string, and you can observe the changes in the string.

<html>
<head>
   <title> JavaScript − Immutable String </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");
      let str = "Animal";
      str[0] = 'j';
      output.innerHTML += "The string is: " + str + "<br>";
      str = "Hi!";
      output.innerHTML += "The updated string is: " + str;
   </script>
</body>
</html>
The string is: Animal
The updated string is: Hi!

Escape Characters

你可以使用反斜杠 (\) 字符和字符串一起使用特殊字符。以下是特殊字符的列表。

You can use the special characters with the string using the backslash (\) characters. Here is the list of special characters.

Escape character

Description

\"

Double quote

\'

Single quote

|Backslash

\n

New line

\t

Tab

\b

backspace

\f

Form feed

\v

Verticle tab

\r

Carriage return

\uXXXX

在下面的示例中,我们在 str1 字符串的字符之间添加了一个单引号,在 str2 字符串的字符之间添加了一个反斜杠。

In the example below, we added a single quote between the characters of the str1 string and a backslash between the characters of the str2 string.

<html>
<head>
   <title> JavaScript - Escape Characters </title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");
      let str1 = "Your\'s welcome!";
      let str2 = "Backslash \\";
      output.innerHTML += "str1 == " + str1 + "<br>";
      output.innerHTML += "str2 == " + str2 + "<br>";
   </script>
</body>
</html>
str1 == Your's welcome!
str2 == Backslash \

String HTML Wrappers

以下是返回用适当的 HTML 标签包装的字符串副本的方法列表。

Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.

Sr.No.

Method & Description

1

anchor() Creates an HTML anchor that is used as a hypertext target.

2

big() Creates a string to be displayed in a big font as if it were in a <big> tag.

3

blink() Creates a string to blink as if it were in a <blink> tag.

4

bold() Creates a string to be displayed as bold as if it were in a <b> tag.

5

fixed() Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag.

6

fontcolor() Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.

7

fontsize() Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.

8

italics() Causes a string to be italic, as if it were in an <i> tag.

9

link() Creates an HTML hypertext link that requests another URL.

10

small() Causes a string to be displayed in a small font, as if it were in a <small> tag.

11

strike() Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.

12

sub() Causes a string to be displayed as a subscript, as if it were in a <sub> tag.

13

sup() Causes a string to be displayed as a superscript, as if it were in a <sup> tag.

在以下部分中,我们将演示几个示例来展示 String 方法的用法。

In the following sections, we will have a few examples to demonstrate the usage of String methods.