Javascript get a specific character in a string. Basic string functions. String Basics

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

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

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

Creating and viewing a string

There are three ways to create a string in JavaScript: they can be written inside single quotes (‘), double quotes (‘), or backticks (`). Although scripts sometimes contain all three types of strings, only one type of quotation mark should be used within a single line.

Single- and double-quoted strings are essentially the same thing. There are no conventions regarding the use of one type of quotation marks or another, but it is generally recommended to use one 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 inside backquotes (also called a backtick) and work the same way as regular strings With several additional functions which we will look at in this article.

`This string uses backticks.`;

The easiest way to view the output of a string 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.

To others in a simple way to request the value of a string is a popup window in the browser that can be called using 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 used less frequently because alerts need to be closed constantly.

Storing strings in variables

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

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

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

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

By assigning strings to variables, you don't have to retype the string each time you want to output it, making 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 the addition operator in mathematical operations.

For example, try concatenating two short strings:

"Sea" + "horse";
Seahorse

Concatenation joins the end of one string to the beginning of another string without inserting spaces. To have a space between lines, it must be added to the end of the first line.

"Sea" + "horse";
Sea horse

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



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

The 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 the string. Instead of concatenation, you can use the $() syntax to insert a variable.

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

This syntax allows you to get the same result. Template literals make string concatenation easier.

String literals and string values

As you may have noticed, all strings are written in quotes or backquotes, but when output, the string does not contain quotes.

"Beyond the Sea";
Beyond the Sea

A string literal is a string as it appears in source code, including quotes. The string value is the string that appears in the output (without the quotes).

IN 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, JavaScript will interpret an apostrophe in the middle of a single-quoted string as a closing single quote, and attempt to read the rest of the intended string as code.

Consider this example:

const brokenString = "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 symbols.
  • Template literal.

Alternative string syntax

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

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

Strings with quotes 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 the syntax in the project files, making them difficult to maintain.

Escape character \

By using a backslash, JavaScript will prevent quotes from being interpreted as closing quotes.

The combination \' will always be treated as an apostrophe and \" as double quotes, no exceptions.

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

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

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

Template literals

Template literals are defined by backquotes, 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 when displaying quotes and apostrophes, but also provide support for inline expressions and multiline blocks, as discussed in the next section.

Multiline lines and newline

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

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

This will split the output into multiple lines. However, if the code contains long lines, they will be difficult to work with and read. To display one string on multiple lines, use the concatenation operator.

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

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

const threeLines = "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 eliminates concatenation and escape characters.

const threeLines = `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 break on a new line and create multi-line 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:

Object-oriented capabilities and associative arrays JavaScript, as a semantic “framework” for using functions and constructs for processing strings, is of particular interest for programming information processing processes based on its semantic content. On JavaScript functions for working with strings can be combined into their own semantic constructs, simplifying the code and formalizing subject area tasks.

In the classical version, information processing is primarily string functions. Each function and construct of the language has its own characteristics in the syntax and semantics of JavaScript. The 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, contenation, change case...

Description of string variables

The var construct is used to declare a string. You can immediately set its value or generate 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 "".

A string denoted by double quotes requires escaping the inner double quotes. Likewise, 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, one should never forget that (in the context of the descriptions made):

  • str_isV => "V";
  • str_chr => “’”;
  • str_dbl => "a".

That is, the characters of the string are available as array elements, with each special character is one character. Escaping is an element of syntax. No “screen” is placed on the actual line.

Using the charAt() function has a similar effect:

  • str_isV.charAt(3) => "V";
  • str_chr.charAt(1) => “’”;
  • str_dbl.charAt(5) => “a”.

The programmer can use any option.

Basic String Functions

JavaScript handles strings a little differently than other languages. The name of the variable (or the string itself) is followed by the name of the function, separated by a dot. Typically, 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 = str_isV.length + '/' + str_chr.length + '/' + str_dbl.length.

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

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

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

In the first case, the string is split at the delimiter character “s” into an array of elements in which the number of elements does not exceed the value “l”. If the quantity is not specified, the entire line is broken.

In the second case, the array of elements is merged into one line through a given delimiter.

A notable feature of this pair: splitting can be done using one separator, and merging can be done using another. In this context, JavaScript can work with strings "outside" the language's syntax.

Classic string functions

Common string processing functions:

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

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

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

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

  • str = str1 + str2 + str3;

Using the charAt() function also makes sense, but using charCodeAt() has real practical meaning. Similarly, for JavaScript, a line break has a special meaning: in the context of displaying, for example, in an alert() message, it is “n”; in a page content generation construct, 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 a mechanism regular expressions. This allows complex searches, fetching, and string conversions to be performed within the browser without contacting the server.

The match method finds and replace replaces the found match with the desired value. Regular expressions are implemented in JavaScript in 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 using the match, search and replace methods, you should not only pay due attention to testing on the entire range of acceptable values ​​of the initial parameters and search strings, but also evaluate the load on the browser.

Regular expression examples

The scope of regular expressions for processing strings is extensive, but requires great care and attention from the developer. First of all, regular expressions are used when testing user input in form fields.

Here are functions that check whether the input contains an integer (schInt) or a real number (schReal). The following example shows how efficient it is to process strings by checking them for only valid characters: schText - text only, schMail - correct address Email.

It is very important to keep in mind that in JavaScript, characters and strings require increased attention to locale, especially when you need to work with Cyrillic. In many cases, it is advisable to specify 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 complete the task as it is set. In particular, with regard to checking integers and real numbers: you can get by not with classic 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 good reason to use them in their original form. The syntax and quality of the functions are impeccable, but it is a one-size-fits-all solution.

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

The ideal solution is always to interpret data for its meaning.

By representing each parameter as an object, you can formulate functions to work with it. Always we're talking about about symbol processing: numbers or strings are sequences of symbols organized in a specific way.

Eat general algorithms, and there are private ones. For example, a 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 allowed, and there may be hyphens or indices separated by a slash. Indexes can be alphabetic or numeric. The house may have buildings.

It is not always possible to foresee all situations. This important point in programming. It is rare that an algorithm does not require modification, 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 and allows it to be brought 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 talk about what is strings in JavaScript and methods of working with them.

Strings are simply groups of characters, such as "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 need to use them very often. Many things such as URL pages, values CSS parameters and form input elements are all strings.

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

String Basics

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

Using quotes

When you announce strings in JavaScript or work with them, always enclose them in single or double quotes. This tells the browser that it is dealing with a string. Do not mix the use of quotes in your code; if you start a line with a single quote and end with a double quote, JavaScript will not understand what you meant. Typically, I use single quotes when working with 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 = "Hello world!"; var b = "I am a student.";

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

Var b = "I"m a student.";

The string contains an extra single quote, and JavaScript thinks the string is complete and displays an error message without understanding what comes next. Therefore you need escape quote, telling the browser to treat it as a character and not as a line ending. This is done using a backslash before the quote:

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

Note that you can insert double quotes into a string without escaping them. Since you are using single quotes to start and end the string,

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

perceived without problems. Double quotes are automatically treated as parts of a string rather than 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 a substring from the string “b” consisting of the second to fourth characters and insert them into the middle of the string “a”, or determine which character is the 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 = "Hello world!".length;

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

Var c = a.length;

Remember that you can use "length" for any string - it's 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 ​​require you to specify whether a variable is a number or a string before doing anything else with it. JavaScript is easier refers to the difference between strings and numbers. In fact, you can even add numbers with strings:

Var c = a + 12;

In some programming languages, processing such a string will result in an error. After all, “a” is a string, and “12” is a number. However, JavaScript tries to solve the problem by assuming that "12" is also a string. Thus "c" becomes "Hello world!12". This means that if you use "+" with a string and a number, JavaScript tries to make the number a string. If you apply mathematical operations to a string, JavaScript tries to turn it into a number. If it is not possible 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, in JavaScript there is no difference between integers and floating point numbers.

Number → string

For number to string conversion enter:

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

You can then apply all string methods to "d" and "c" still contains a number.

String → number

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

Var c = "1234"; d = c * 1;

Since multiplication only works with numbers, JavaScript turns the string into a number if possible. Otherwise, the result is NaN.

Note that if you write:

Var c = "1234"; d = c + 0;

The result will be "12340" because JavaScript uses "+" to concatenate strings rather than adding them.

String Properties and Methods

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

String_name.method();

List of built-in JavaScript methods for working with strings

Concatenation - joining 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 there to be space between sentences. To do this, write the code as follows:

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

So we will connect three strings: “a”, ““”” (one space) and “b”, resulting in: “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”, considered as a string, and “b”, getting: “Hello world!9 I am a student. »

You need to be careful when using addition. Team

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

connects 4 strings: "a", "3", "3" and "b" because "+" in in this case means “to join the lines”, not “to add” and the result is: “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 connects the string “a”, the result of the expression “3 + 3” and “b”, resulting in: “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 line. Note that the index of the first character is 0, the second is 1, etc. Thus, the index of the character “w” in the string “a” is 6.

Using "indexOf" we can output the index of a character. Write ".indexOf(" ")" after the line name and insert the character you are looking for between the quotes. For example:

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

will return 6 . If a character occurs multiple times, this method returns the first occurrence. That is

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 symbols. (Of course, this is also a string, but to avoid confusion, I won't call it that). "indexOf" returns the position of the first character of the combination. For example:

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

will also return 4 because it is the index of "o".

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

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

then you will 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 the character or combination does not occur in the string, "indexOf" will return "-1". This is essentially the most popular use of "indexOf": checking for the existence of a certain 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") != -1) ( //Any actions with Internet Explorer)

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

lastIndexOf

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

Var b = "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 = "I am a student."; document.write(b.charAt(5));

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

length

The "length" method returns the length of the string.

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

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

split

"split" is a special method that allows you to split a string at specific characters. Used when the result needs to be stored in an array rather than in a simple variable. Let's split "b" by spaces:

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

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

Temp = "I"; temp = "am"; temp = "a"; temp = "student";

The "substring" method is used to subtract part of a string. Method syntax: ".substring(first_index, last_index)". For example:

Var a = "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 = "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. That is

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

returns 8 characters, starting from the character at index 4 (“o”), that is, the result is: “ o world! »

toLowerCase and toUpperCase

Finally, 2 methods that can sometimes be useful to you: “toLowerCase” converts the entire string to lower case, and “toUpperCase” converts it to upper case.

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

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

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

We have already briefly become acquainted with the string type and, in fact, we only learned what a string is and how it is written. Let's now take a closer look at strings and methods for working with them.

As you remember, any text in JavaScript is a string. The string must be enclosed in quotes, single or double, it makes no difference:

var hi = "hello", name = "John";

var hi = "hello" ,

name = "John" ;

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

var text = "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 = "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 with new paragraph a new line. Let's try adding a line break like this 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 line break in this interpretation:

Syntax error, as expected. How to be? There are several ways to store multiline text in a variable. You might have already guessed about 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 the backslash (\), which in JavaScript and many other programming languages ​​is an escape character that allows you to safely work with special characters. We will learn what special characters are further. So let's try to screen invisible symbol line feed:

Shielding also solved our problem. However, if we look at the console, both string concatenation and line feed escaping, while solving the problem of writing to the program, did not solve the problem of displaying a multiline string on the screen. Instead of a multi-line line, we will see one-line text in the console. What should I do?

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

var text = "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 = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nobis dignissimos maxime et tempore omnis, ab fugit.\

"Quos nisi, culpa exercitationem!";

console. log(text);

Actually, if you don’t mind writing the text in the code in one line, then we can do it like this:

var text = "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 = "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; we will see multi-line text in the browser console:

We really don’t really need the backslash escape character in the code in this situation. But it is actually needed, as noted above, for escaping special characters. For example, inside a string that we enclosed in single quotes, there is an apostrophe, i.e. single quote:

var text = "Lorem ipsum d"olor sit amet";

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

Var name1 = "Tommy";

So use the String constructor:

Var name1 = new String("Tommy");

The first method is mainly used, probably because it is shorter.

Class for working with String has quite a lot in its arsenal big set properties and functions with which you can perform various manipulations with strings.

String length

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

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

Search in a string

In order 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) are used. These functions take two arguments:

  • The substring that actually needs to be found
  • An optional argument that specifies from which character to search for a substring in a string

Both of these functions return a number, which 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 a string contains a substring or not, then in this case the result of these functions is compared with -1.

Var str1 = "Hello Vasya!"; var podstr = "Petya"; if(str.indexOf(podstr) == -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 “Peter” 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 line, starting from which the line will be trimmed
  • end position to which the string should be trimmed
var hello1 = "hello world. Goodbye world"; var world1 = hello1.substring(7, 10); //from 7th to 10th index document.write(world1); //world

The substr() function also takes the starting index of the substring as the 1st parameter, and the length of the substring as the 2nd parameter:

Var hello1 = "hello world. Goodbye world"; var bye1 = 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 = "hello world. Goodbye world"; var bye1 = hello1.substr(12); document.write(bye1); //bye peace

Letter case control

To change the case of letters, that is, to make all letters small or capital, 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 big).

Var hello1 = "Hello Jim"; document.write(hello1.toLowerCase() + "
"); //hi Jim document.write(hello1.toUpperCase() + "
"); //HELLO JIM

Getting a symbol 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 character index as an argument:

Var hello1 = "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 the result of its work, then the charCodeAt() function will return the numeric Unicode code of this character.

Removing spaces

To remove spaces in a string, use the trim() function:

Var hello1 = "Hello Jim"; var beforeLen = hello1.length; hello1 = hello1.trim(); var afterLen = hello1.length; document.write("Line length up to: " + beforeLen + "
"); //15 document.write("Length of line after: " + afterLen + "
"); //10

Concatenating Strings

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

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

Substring replacement

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

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

The first argument of the function indicates which substring should be replaced, and the 2nd argument indicates which substring should be replaced with.

Splitting a string into an array

The split() function allows you to split a string into an array of substrings using a specific delimiter. You can use a string that is passed to the method:

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

RESULTS

Strings can be created simply using a regular 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 a string, then such numbers can be compared incorrectly; for this, the string needs to be converted to the type number (read about the Number class).

Also, when comparing strings, you should take into account the case of letters. Capital letter less than a small one, and the letter е is outside the alphabet in general.

TASKS

Changing the case of the last letter in a string

Write a function lastLetterStr(str) that will change the case of the last letter, making it capital.

Spam check

Write a function provSpam(str) that will check a string for the presence of 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 number function should return. For example, there is a line “120 UAH” that needs to be returned from line 120.

And to reinforce this, watch the video on working with strings in JavaScript.