Javascript string manipulation. Working with strings in javascript: full debriefing with string variables

Hello! In this tutorial, we'll take a look at how JavaScript can create a string and string functions. Basically, in JavaScript, any text variable is a string, since JavaScript is not a strongly typed programming language (read about data types). And also the String class is used to work with strings:

Var name1 \u003d "Tommy";

So use the String constructor:

Var name1 \u003d new String ("Tommy");

The first method is mainly used, probably because it is more concise.

The class for working with strings String has in its arsenal a fairly large set of properties and functions with which you can perform various manipulations with strings.

Line length

The length property allows you to set the length of the string. This property returns a number:

Var hello1 \u003d "hello world"; document.write ("In the line" "+ hello +" "" + hello1.length + "characters");

Search in string

To find a certain substring in a string, the functions indexOf () (returns the index of the first occurrence of the substring) and lastIndexOf () (returns the index of the last occurrence of the substring). These functions take two arguments:

  • The substring to be found
  • An optional argument that indicates from which character to search for a substring in the string

Both of these functions return a number that is the index of the character at which the substring begins in the string. If the substring is not found, the number -1 will be returned. Therefore, these functions are used in logical operators, because as a rule, you just need to check whether the string contains a substring or not, in this case the result of these functions is compared with -1.

Var str1 \u003d "Hello Vasya!"; var podstr \u003d "Petya"; if (str.indexOf (podstr) \u003d\u003d -1) (document.write ("Substring not found.");) else (document.write ("Substring found.");)

In the example, the message "Substring not found" will be displayed, since the string "Petya" is not contained in the string "Hello Vasya!"

Substring selection

To cut a substring from a string, functions such as substr () and substring () are used.

The substring () function takes 2 arguments:

  • the starting position of the character in the string, from which the string will be trimmed
  • the end position to which to trim the string
var hello1 \u003d "hello world. Goodbye world"; var world1 \u003d hello1.substring (7, 10); // 7th to 10th index document.write (world1); //world

The substr () function also takes the starting index of the substring as the first parameter, and the length of the substring as the second:

Var hello1 \u003d "hello world. Goodbye world"; var bye1 \u003d hello1.substr (12, 2); document.write (bye1); // Before

And if the 2nd parameter is not specified, then the line will be truncated to the end:

Var hello1 \u003d "hello world. Goodbye world"; var bye1 \u003d hello1.substr (12); document.write (bye1); // bye the world

Letter case control

To change the case of letters, that is, to make all letters small or large, use the functions toLowerCase () (to convert characters to lower case, that is, all letters will be small) and toUpperCase () (to convert characters to upper case, that is, all letters will be great).

Var hello1 \u003d "Hello Jim"; document.write (hello1.toLowerCase () + "
"); // hello jim document.write (hello1.toUpperCase () +"
"); // HELLO JIM

Getting a character by its index

In order to find a specific character in a string by its index, the charAt () and charCodeAt () functions are used. Both of these functions take a symbol index as an argument:

Var hello1 \u003d "Hello Jim"; document.write (hello1.charAt (3) + "
"); // in document.write (hello1.charCodeAt (3) +"
"); //1080

But only if the charAt () function returns the character itself as a result of its work, the charCodeAt () function will return the numeric Unicode code of this character.

Removing spaces

The trim () function is used to remove spaces in the stock:

Var hello1 \u003d "Hello Jim"; var beforeLen \u003d hello1.length; hello1 \u003d hello1.trim (); var afterLen \u003d hello1.length; document.write ("Line length before:" + beforeLen + "
"); // 15 document.write (" Line length after: "+ afterLen +"
"); //10

Concatenating strings

The concat () function allows you to concatenate 2 strings:

Var hello1 \u003d "Hello"; var world1 \u003d "Vasya"; hello1 \u003d hello1.concat (world1); document.write (hello); //Hello, Vasya

Substring replacement

The replace () function allows you to replace one substring with another:

Var hello1 \u003d "Good afternoon"; hello1 \u003d hello1.replace ("day", "evening"); document.write (hello1); //Good evening

The first argument of the function indicates which substring should be replaced, and the second argument indicates which actual substring should be replaced.

Splitting a string into an array

The split () function allows you to split a string into an array of substrings using a specific delimiter. As it, you can use a string that you pass to the method:

Var mes \u003d "The weather was wonderful today"; var stringArr \u003d mes.split (""); for (var str1 in stringArr) document.write (stringArr + "
");

RESULTS

Strings can be created simply using an ordinary variable, just put text in it or using the String class.

To find out the length of a string, use the length property.

Strings are compared letter by letter. Therefore, if there is a number in the string, then such numbers may not be compared correctly, for this the string needs to be converted to the type number (read about the Number class).

Also, when comparing strings, consider the case of letters. Capital letter less small, and the letter e is outside the alphabet in general.

TASKS

Changing the case of the last letter in a string

Write a function lastLetterStr (str) that replaces the case of the last letter by making it large.

Spam check

Write the provSpam (str) function that will check the string for substrings: "spam", "sex", "xxx". And return true if there is substring data and false otherwise.

Find the number

Write a function extrNum (str) that gets a number from a string if the string contains a number and the function should return a number. For example, there is a line "120 UAH" that needs to be returned from line 120.

And for pinning, watch the video on working with strings in JavaScript.

As a semantic "framework" for the use of functions and constructions for processing strings, they are of particular interest for programming information processing processes based on its semantic content. In language JavaScript functions work with strings can be combined into your own semantic constructs, simplifying the code and formalizing subject area tasks.

In the classical version, information processing is, first of all, string functions. Each function and structure of the language has its own peculiarities in the syntax and semantics of JavaScript. Methods for working with strings here have their own style, but in common use it is just syntax within simple semantics: search, replace, insert, extract, contain, change case ...

Description of string variables

To declare a string, use the construction var. You can immediately set its value or form it during the execution of the algorithm. You can use single or double quotes for a string. If it must contain a quotation mark, it must be escaped with the "\\" character.

The line denoted requires escaping the inner double quotes. Similarly, the one marked with single quotes is critical to the presence of single quotes inside.

IN this example the string "str_dbl" lists useful special characters that can be used in the string. In this case, the character "\\" itself is escaped.

A string is always an array

JavaScript can work with strings in a variety of ways. The language syntax provides many options. First of all, you should never forget that (in the context of the descriptions made):

  • str_isV \u003d\u003e "V";
  • str_chr \u003d\u003e "" ";
  • str_dbl \u003d\u003e "a".

That is, the characters of the string are available as elements of the array, with each special character is one character. Escaping is a syntakis element. No "screen" fits into a real line.

Using the charAt () function has a similar effect:

  • str_isV.charAt (3) \u003d\u003e "V";
  • str_chr.charAt (1) \u003d\u003e "" ";
  • str_dbl.charAt (5) \u003d\u003e "a".

The programmer can use any option.

Basic string functions

JavaScript is implemented slightly differently than other languages. The name of the function is written to the name of the variable (or directly to the string) through a dot. Usually, string functions are called methods in the style of language syntax, but the first word is more familiar.

The most important method of a string (more correctly, a property) is its length.

  • var xStr \u003d str_isV.length + "/" + str_chr.length + "/" + str_dbl.length.

Result: 11/12/175 along the lines of the above description.

The most important pair of string functions is splitting a string into an array of elements and merging an array into a string:

  • split (s [, l]);
  • join (s).

In the first case, the string is split by the separator character "s" into an array of elements, in which the number of elements does not exceed the value "l". If no quantity is specified, the entire line is split.

In the second case, the array of elements is merged into one line through the specified separator.

A remarkable feature of this pair: splitting can be done on one separator, and merging - on another. In this context, in JavaScript, working with strings can be "taken outside" of the syntax of the language.

Classic string functions

Common string processing functions:

  • search;
  • sample;
  • replacement;
  • transformation.

Represented by methods: indexOf (), lastIndexOf (), toLowerCase (), toUpperCase (), concan (), charCodeAt () and others.

In JavaScript, working with strings is represented by a large number of functions, but they either duplicate each other, or are left for old algorithms and compatibility.

For example, using the concat () method is ok, but it's easier to write:

  • str \u003d str1 + str2 + str3;

The use of the charAt () function also makes sense, but the use of charCodeAt () has real practical value. Similarly, for JavaScript, line breaks have a special meaning: in the context of displaying on the screen, for example, in the alert () message, it is "\\ n", in the construction of page content generation, it is "
". In the first case it is just a character, and in the second it is a string of characters.

Strings and Regular Expressions

In JavaScript, working with strings includes the mechanism regular expressions... This allows complex searches, selections, and string transformations to be performed within the browser without going back to the server.

Method match finds, but replace replaces the found match with the desired value. Regular expressions are implemented in JavaScript by high level, in essence, are complex, and due to the specifics of the application, they transfer the center of gravity from the server to the client's browser.

When applying methods match, searchand replace one should not only pay due attention to testing on the entire range of acceptable values \u200b\u200bof the initial parameters and search strings, but also evaluate the load on the browser.

Regular Expression Examples

The use of regular expressions for string processing is extensive, but requires great care and attention from the developer. Regulars are primarily used when testing user input in form fields.

Here are functions that check if the input contains an integer (schInt) or a real number (schReal). The following example shows how efficiently it can process strings by checking for only valid characters: schText is text only, schMail is a valid email address.

It is very important to keep in mind that in JavaScript, characters and strings require extra attention to the locale, especially when working with Cyrillic. In many cases, it is advisable to indicate the actual character codes rather than their meanings. This applies primarily to Russian letters.

It should be especially noted that it is not always necessary to carry out the task as it is set. In particular, with regard to checking integers and real numbers: you can get by not with classical string methods, but with ordinary syntax constructions.

Object oriented strings

In JavaScript, working with strings is represented by a wide range of functions. But this is not a compelling reason to use them in their original form. The syntax and quality of the features are impeccable, but it's a one-size-fits-all solution.

Any use of string functions presupposes the processing of real meaning, which is determined by the data, scope, and specific purpose of the algorithm.

The ideal solution is always to interpret the data in its meaning.

By representing each parameter as an object, you can formulate functions to work with it. It is always about processing characters: numbers or strings are sequences of characters organized in a specific way.

There are general algorithms, and there are private ones. For example, the surname or house number are strings, but if in the first case only Russian letters are allowed, then in the second case numbers, Russian letters are acceptable, and there may be hyphens or indices separated by a slash. Indexes can be alphabetic or numeric. The house can have buildings.

All situations cannot always be foreseen. This is an important point in programming. A rare algorithm does not require improvement, and in most cases it is necessary to systematically adjust the functionality.

Formalization of the processed line information in the form of an object improves the readability of the code, allows you to bring it to the level of semantic processing. This is a different degree of functionality and significantly best quality code with greater reliability of the developed algorithm.

This article will discuss what is strings in JavaScript and methods of working with them.

Strings are just groups of characters like "JavaScript", "Hello world! "," Http://www.quirksmode.org "or even" 14 ". To program in JavaScript, you need to know what strings are and how to work with them, since you will have to use them very often. Many things, such as URL pages, CSS parameter values \u200b\u200band form input elements, are all strings.

First I will try to explain working with stringsthen - the difference between in JavaScript. Even if you have programming experience in another language, please read this part carefully. At the end, I will talk about the most important strings in JavaScript.

String basics

Let's take a look at the basics of working with strings in JavaScript.

Using quotes

When you declare strings in JavaScript or when working with them, always enclose them in single or double quotes. This tells the browser that it is dealing with a string. Do not mix up the use of quotes in your code, if you start a string with a single quote and end with a double quote, JavaScript will not understand what you mean. Generally, I use single quotes for strings, since I chose to use double quotes for HTML and single quotes for JavaScript. Of course, you can do everything differently, but I advise you to come up with a similar rule for yourself.

Let's imagine two lines that we will use throughout the article:

Var a \u003d "Hello world!"; var b \u003d "I am a student.";

Now we have declared two variables, "a" and "b", and assigned string values \u200b\u200bto them. After that we can work with them, but first we will solve one problem: let's say I wrote:

Var b \u003d "I" m a student. ";

The string contains an extra single quote, and JavaScript thinks that the string is complete and prints an error message, not knowing what comes next. Therefore you need escape quote, telling the browser to treat it as a character, not a line end. This is done with a backslash in front of the quote:

Var b \u003d "I \\" m a student. ";

Note that you can insert double quotes in a string without escaping them. Since you are using single quotes as the beginning and end of a string,

Var b \u003d "I \\" m a "student". ";

perceived without problems. Double quotes are automatically treated as part of a string, not a command.

Built-in functions

Once the strings are defined, you can start using them. For example, you can concatenate one string to another, or take from the string "b" a substring consisting of the second-fourth characters and insert them into the middle of the string "a", or determine which character is twelfth in "a", how many characters are in "b", whether they contain the letter " q ", etc.

To do this, you can use the built-in functions that JavaScript predefines for each line. One of them - "length" - returns the length of the string. That is, if you want to calculate the length of "Hello world!", Write:

Var c \u003d "Hello world!". Length;

Earlier we assigned this string to the variable "a". Thus, you have made the variable "a" a string, so the function "length" can also be applied to it, and the following operation will give the same result:

Var c \u003d a.length;

Remember that you can use "length" for any string - this is a built-in function. You can calculate the length of any string, for example: "location.href" or "document.title" or declared by you.

Below I will present a list of common built-in methods and properties.

Strings and numbers

Some programming languages \u200b\u200brequire you to specify whether a variable is a number or a string before doing anything else with it. JavaScript is easier on the difference between strings and numbers. In fact, you can even add numbers to strings:

Var c \u003d a + 12;

In some programming languages, processing such a string will result in an error. Still, "a" is a string, and "12" is a number. However, JavaScript tries to solve the problem by assuming "12" is also a string. Thus, "c" becomes "Hello world! 12". So if you use "+" with a string and a number, JavaScript tries to make a string out of the number. If you apply math to a string, JavaScript tries to convert it to a number. If there is no way to convert a string to a number (for example, due to the presence of letters in it), JavaScript returns NaN - "Not a Number is not a number".

Finally, there is no difference in JavaScript between integers and floating point numbers.

Number -\u003e string

For convert number to string enter:

Var c \u003d (16 * 24) / 49 + 12; d \u003d c.toString ();

After that, you can apply all string methods to "d", and "c" still contains a number.

String -\u003e number

If you want to convert a string to a number, first make sure that it only consists of characters 0-9. To do this, I simply multiply the string by 1.

Var c \u003d "1234"; d \u003d c * 1;

Since multiplication is done only with numbers, JavaScript converts the string to a number if possible. Otherwise, the result is NaN.

Note if you write:

Var c \u003d "1234"; d \u003d c + 0;

The result is "12340" because JavaScript uses "+" to concatenate strings, not concatenate them.

String properties and methods

So what can we do with strings? Concatenation is a special case, but all other commands (methods) can be used on any string using the construct:

String_name.method ();

List of built-in JavaScript methods for working with strings

Concatenation - concatenating strings

First, you can concatenate strings by adding them together, like this:

Document.write (a + b);

the result will be: "Hello world! I am a student. ". But of course you want a space between the sentences. To do this, write the code as follows:

Document.write (a + "" + b);

So we will concatenate three lines: "a", "" "" (one space) and "b", as a result we get: "Hello world! I am a student. "

You can even use numbers or calculations, for example:

Document.write (a + 3 * 3 + b);

Now we concatenate the string "a", then the result of the expression "3 * 3", treated as a string, and "b", getting: "Hello world! 9 I am a student. "

Be careful when using addition. Command

Document.write (a + 3 + 3 + b);

concatenates 4 lines: “a”, “3”, “3” and “b”, because “+” in this case means “concatenate lines”, not “add” and as a result: “Hello world! 33 I am a student. ". If you want to add 3 and 3 before creating a string, use parentheses.

Document.write (a + (3 + 3) + b);

This expression concatenates the string "a", the result of the expression "3 + 3" and "b", in the result: "Hello world! 6 I am a student. ".

indexOf

One of the most widely used built-in methods is "indexOf". Each character has its own index containing the number of its position in the string. Note that the index of the first character is 0, the second is 1, and so on. Thus, the index of the character "w" in the term "a" is 6.

Using "indexOf" we can print the index of the character. Write ".indexOf (" ")" after the string name and insert the character you are looking for between the quotes. For instance:

Var a \u003d "Hello world!"; document.write (a.indexOf ("w"));

will return 6. If the character occurs multiple times, this method returns the first occurrence. I.e

Document.write (a.indexOf ("o"));

will return 4 because it is the index of the first "o" in the string.

You can also search for a combination of characters. (Of course, this is also a string, but to avoid confusion, I will not call it that). "IndexOf" returns the position of the first character of the combination. For instance:

Document.write (a.indexOf ("o w"));

will also return 4, because it's index "o".

Moreover, it is possible to search for a character after a certain index. If you enter

Document.write (a.indexOf ("o", 5));

then get the index of the first "o" following the character with index 5 (this is a space), that is, the result will be - 7.

If a character or combination does not appear in the string, "indexOf" will return "-1". This is, in fact, the most popular use for "indexOf": checking for the existence of a specific combination of characters. It is the core of the script that defines the browser. To define IE, you take the line:

Navigator.userAgent;

and check if it contains "MSIE":

If (navigator.userAgent.indexOf ("MSIE")! \u003d -1) (// Any action with Internet Explorer)

If the index "MSIE" is not "-1" (if "MSIE" occurs anywhere in the string), then the current browser is IE.

lastIndexOf

There is also a "lastIndexOf" method that returns the last occurrence of a character or combination. It acts the opposite of "indexOf". Command

Var b \u003d "I am a student."; document.write (b.lastIndexOf ("t"));

will return 13 because it is the index of the last "t" in the string.

charAt

The "charAt" method returns the character at the specified position. For example, when you enter

Var b \u003d "I am a student."; document.write (b.charAt (5));

the result is "a" since it is the sixth character (remember that the index of the first character starts at 0).

length

The length method returns the length of the string.

Var b \u003d "I am a student."; document.write (b.length);

will return "15". The string length is 1 longer than the index of the last character.

split

"Split" is a special method that allows you to split a string based on specific characters. It is used when the result needs to be entered into an array, and not into a simple variable. Let's split the "b" by spaces:

Var b \u003d "I am a student." var temp \u003d new Array (); temp \u003d b.split ("");

Now the string is split into 4 substrings, which are placed in the "temp" array. The gaps themselves have disappeared.

Temp \u003d "I"; temp \u003d "am"; temp \u003d "a"; temp \u003d "student";

The substring method is used to select a portion of a string. Method syntax: ".substring (first_index, last_index)". For instance:

Var a \u003d "Hello world!"; document.write (a.substring (4, 8));

will return "o wo", from the first "o" (index 4) to the second (index 7). Note that "r" (index 8) is not part of the substring.

You can also write:

Var a \u003d "Hello world!"; document.write (a.substring (4));

This will give the whole substring “o world! ", Starting from the character with index 4 to the end of the line.

substr

There is also a "substr" method that works a little differently. It does not use the index number as the second argument, but the number of characters. I.e

Document.write (a.substr (4, 8));

returns 8 characters starting from the character with index 4 ("o"), that is, the result is: "o world! "

toLowerCase and toUpperCase

Finally, there are 2 methods that you might find useful sometimes: "toLowerCase" converts the entire string to lowercase, and "toUpperCase" to uppercase.

Var b \u003d "I am a student."; document.write (b.toUpperCase ());

As a result, we get “I AM A STUDENT. ".

A string is a sequence of one or more characters that can contain letters, numbers, and other characters. In JavaScript, this is the simplest immutable data type.

Strings allow you to display and work with text, and text is the primary way to communicate and communicate information on the web. Therefore, strings are one of the main concepts in programming.

This tutorial will teach you how to create and view the output of strings, concatenate strings and store them in variables. You will also learn about the rules for using quotation marks, apostrophes, and newlines in JavaScript.

Creating and viewing a string

There are three ways to create strings in JavaScript: you can write them in single quotes (‘), in double quotes (“), or in back quotes (`). Although sometimes all three types of strings appear in scripts, you only need to use one type of quotation marks within a single string.

Single quoted strings and double quoted strings are essentially the same thing. There are no conventions regarding the use of one or the other type of quotation marks, but it is usually recommended to use a single type consistently in program scripts.

"This string uses single quotes.";
"This string uses double quotes.";

Third and newest way creating a string is called a template literal. Template literals are written in backticks (also called grave accent) and work just like regular strings with a few additional functions, which we'll cover in this article.

`This string uses backticks.`;

The easiest way to view the output of a line is to enter it into the console using console.log ().

console.log ("This is a string in the console.");
This is a string in the console.

Others in a simple way to request a string value is a popup in the browser that can be called with alert ():

alert ("This is a string in an alert.");

This line will open a notification window in the browser with the following text:

This is a string in an alert.

The alert () method is less commonly used because alerts need to be closed all the time.

Storing strings in variables

Variables in JavaScript are named containers that store values \u200b\u200busing keywords var, const or let. Strings can be assigned to variables.

const newString \u003d "This is a string assigned to a variable.";

The newString variable now contains a string that can be referenced and printed using the console.

console.log (newString);
This is a string assigned to a variable.

By assigning strings to variables, you don't have to re-enter the string every time you want to output it, which makes it easier to work with strings within programs.

String concatenation

String concatenation is the process of combining two or more strings into one new line... Concatenation is done using the + operator. The + symbol is also an addition operator in mathematical operations.

For example, try combining two short lines:

"Sea" + "horse";
Seahorse

Concatenation concatenates the end of one line with the beginning of another line without inserting spaces. To have a space between the lines, add it to the end of the first line.

"Sea" + "horse";
Sea horse

Concatenation allows you to concatenate strings and variables with string values.



const favePoem \u003d "My favorite poem is" + poem + "by" + author ".";

New strings resulting from concatenation can be used in the program.

Variables with Template Literals

One of the features of template literals is the ability to include expressions and variables in a string. Instead of concatenation, you can use the $ () syntax to insert a variable.

const poem \u003d "The Wide Ocean";
const author \u003d "Pablo Neruda";
const favePoem \u003d `My favorite poem is $ (poem) by $ (author) .`;
My favorite poem is The Wide Ocean by Pablo Neruda.

This syntax produces the same result. Template literals make string concatenation easier.

String literals and string values

As you may have noticed, all strings are quoted or backquoted, but the string does not contain quotation marks in the output.

"Beyond the Sea";
Beyond the Sea

A string literal is a string as it looks in source codeincluding quotes. A string value is a string that appears in the output (without quotes).

In this example, "Beyond the Sea" is a string literal and Beyond the Sea is a string value.

Traversing quotes and apostrophes in strings

Because quotation marks are used to denote strings, there are special rules for using apostrophes and quotation marks in strings. For example, an apostrophe in the middle of a single quoted string will be interpreted by JavaScript as a closing single quote, and the rest of the intended string will try to read as code.

Consider this example:

const brokenString \u003d "I" m a broken string ";
console.log (brokenString);
unknown: Unexpected token (1:24)

The same thing happens if you try to use double quotes inside a double quoted string. The interpreter will not notice the difference.

To avoid such errors, you can use:

  • Different string syntax.
  • Escape characters.
  • Template literal.

Alternative string syntax

The easiest way to work around this problem is with the opposite syntax to the one you use in the script. For example, enclose strings with apostrophes in double quotes:

"We" re safely using an apostrophe in double quotes. "

Quote strings can be enclosed in single quotes:

"Then he said," Hello, World! "";

By combining single and double quotes, you can control the display of quotes and apostrophes within strings. However, this will affect the consistency of syntax in the project files and will be difficult to maintain.

Escape character \\

With a backslash, JavaScript will not interpret the quotes as closing quotes.

The combination \\ ’will always be interpreted as an apostrophe, and \\” as double quotes, without exception.

This allows apostrophes to be used in single-quoted strings, and quotes in double-quoted strings.

"We \\" re safely using an apostrophe in single quotes. "
"Then he said, \\" Hello, World! \\ "";

This method looks a little messy. But it is required if the same line contains both an apostrophe and double quotes.

Template literals

Template literals are defined with backticks, so both double quotes and apostrophes can be safely used without any additional manipulation.

`We" re safely using apostrophes and "quotes" in a template literal.`;

Template literals not only avoid errors in the display of quotation marks and apostrophes, but also provide support for inline expressions and multi-line blocks, which are discussed in the next section.

Multiline lines and line breaks

In some situations, there is a need to insert a newline character or a line break. The escape characters \\ n or \\ r will help you insert a new line into the code output.

const threeLines \u003d "This is a string \\ nthat spans across \\ nthree lines.";
This is a string
that spans across
three lines.

This will split the output across multiple lines. However, if there are long lines in the code, they will be difficult to work with and read. To display one line across multiple lines, use the concatenation operator.

const threeLines \u003d "This is a string \\ n" +
"that spans across \\ n" +
"three lines.";

You can also escape the newline by using the \\ escape character.

const threeLines \u003d "This is a string \\ n \\
that spans across \\ n \\
three lines. ";

Note: This method is not recommended as it may cause problems in some browsers.

To make your code readable, use template literals. This avoids concatenation and escape characters.

const threeLines \u003d `This is a string
that spans across
three lines.`;
This is a string
that spans across
three lines.

Since different code bases may use different standards, it is important to know all the ways to go to a new line and create multiline strings.

Conclusion

Now you know the basic principles of working with strings in JavaScript, you can create strings and template literals, perform concatenation and traversal, and assign strings to variables.

Tags:

From the author: I greet you friends. In several previous articles, we introduced you to the numeric data type in JavaScript and worked with numbers. Now it's time to work with strings in JavaScript. Let's take a closer look at the string data type in JavaScript.

In we have already briefly got acquainted with the string type and, in fact, we just learned what a string is and how it is written. Let's now take a closer look at strings and how to work with them.

Remember, any text in JavaScript is a string. The string must be enclosed in quotes, single or double, no difference:

var hi \u003d "hello", name \u003d "John";

var hi \u003d "hello",

name \u003d "John";

Now we have written only one word to the variables. What if we want to record a large amount of text? No problem, let's write some fish text into a variable and output it to the console:

var text \u003d "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit. Quos nisi, culpa exercitationem!"; console.log (text);

var text \u003d "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit. Quos nisi, culpa exercitationem!";

console. log (text);

Works. But if there is a lot of text, we will probably have line breaks to start a new paragraph on a new line. Let's try to add this line break to our text:

As you can see, my text editor already highlighted in red possible problem... Let's see how the browser reacts to a newline in this interpretation:

Syntax error, as you would expect. How to be? There are several ways to write multi-line text to a variable. You might have already guessed one of them, we are talking about string concatenation:

As you can see, the editor already reacts normally to this option of writing a string to a variable. Another option is to use a backslash (\\), which in JavaScript and in many other programming languages \u200b\u200bis an escape character that allows you to safely work with special characters. We will find out what special characters are later. So, let's try escaping an invisible line feed character:

Shielding also solved our problem. However, if we look into the console, then both string concatenation and line feed escaping, having solved the problem of writing to the program, did not solve the problem with displaying a multi-line string to the screen. Instead of a multi-line string, we will see one line text in the console. How to be?

And here the special newline character \\ n will help us. By adding this special character to the line in the right place, we tell the interpreter that at this point it is necessary to terminate the current line and make a new line.

var text \u003d "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit. \\ \\ nQuos nisi, culpa exercitationem!"; console.log (text);

var text \u003d "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit. \\

\\ nQuos nisi, culpa exercitationem! ";

console. log (text);

Actually, if you are not confused by writing the text in the code in one line, then we can do it like this:

var text \u003d "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit. \\ nQuos nisi, culpa exercitationem!"; console.log (text);

var text \u003d "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit. \\ NQuos nisi, culpa exercitationem!";

console. log (text);

The result on the screen will not change from this, we will see multi-line text in the browser console:

The backslash escape character in the code is really not really necessary to us in this situation. And it is actually needed, as noted above, for escaping special characters. For example, inside a string that we have enclosed in single quotes, there is an apostrophe, i.e. single quote:

var text \u003d "Lorem ipsum d" olor sit amet ";

Did you like the article? To share with friends: