Javascript line starts with. Standard String Object Methods

In this article we'll talk about what it 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, CSS values-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 to work with strings, since I decided 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 part of a string, not a command.

Built-in functions

Once the strings have been 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 the following 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 may 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. "

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 the tongue JavaScript functions operations with strings can be combined into your own semantic constructions, simplifying the code and formalizing subject area tasks.

In the classical version, information processing is, first of all, 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 in this example the line “str_dbl” lists useful Special symbols, which can be used in a 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 in a string are available as array elements, with each special character being 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 regular expression mechanism. 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 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 across the entire spectrum acceptable values 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 presented wide range 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. We are always talking about processing symbols: 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.

As semantic “frameworks” for the use of functions and constructions for processing strings, they are of particular interest for programming information processing processes according to its semantic content. On JavaScript functions for working with strings can be combined into their own semantic constructs, simplifying the code and formalizing the subject area of ​​the task.

In the classical version, information processing is, first of all, 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, insertion, extraction, connotation, change case...

Description of string variables

To declare a string, use the construction var. 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.

The line indicated requires escaping the internal 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 in a string are available as array elements, with each special character being 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

In JavaScript it is done a little differently than in 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(), 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 regular expression mechanism. This allows complex searches, fetching, and string conversions to be performed within the browser without contacting the server.

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

When applying methods match, search And replace You should not only pay due attention to testing over 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 - valid email address.

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. We are always talking about processing symbols: numbers or strings are sequences of symbols organized in a specific way.

There are 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 is an 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 better code quality with greater reliability of the developed algorithm.

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 the string data type 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 a string in in the right place, we will tell the interpreter to terminate at this point current line and make the transition to 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";

Greetings to everyone who has thoroughly decided to learn a prototype-oriented language. Last time I told you about it, and today we will look at JavaScript strings. Since in this language all text elements are strings (there is no separate format for characters), you can guess what this section occupies significant part in learning js syntax.

That is why in this publication I will tell you how string elements are created, what methods and properties are provided for them, how to correctly convert strings, for example, convert to a number, how you can extract the desired substring and much more. In addition to this I will attach examples program code. Now let's get down to business!

String variable syntax

In the js language, all variables are declared using keyword var, and then, depending on the format of the parameters, the type of the declared variable is determined. As you remember from JavaScript, there is no strong typing. That is why this situation exists in the code.

On initialization variable values can be framed in double, single, and starting from 2015, in skewed single quotes. Below I have attached examples of each method of declaring strings.

I want to pay special attention to the third method. It has a number of advantages.

With its help, you can easily carry out a line break and it will look like this:

alert(`several

I'm transferring

And the third method allows you to use the $(…) construction. This tool is needed to insert interpolation. Don’t be alarmed, now I’ll tell you what it is.

Thanks to $(…) you can insert not only the values ​​of variables into lines, but also perform arithmetic and logical operations, call methods, functions, etc. All this is called one term - interpolation. Check out an example implementation of this approach.

1 2 3 var pen = 3; var pencil = 1; alert(`$(pen) + $(pencil*5) = $(pen + pencil)`);

var pen = 3; var pencil = 1; alert(`$(pen) + $(pencil*5) = $(pen + pencil)`);

As a result, the expression “3 + 1*5 = 8” will be displayed on the screen.

As for the first two ways of declaring strings, there is no difference in them.

Let's talk a little about special characters

Many programming languages ​​have special characters that help manipulate text in strings. The most famous among them is line break (\n).

All similar tools initially begin with a backslash (\) and are followed by letters of the English alphabet.

Below I have attached a small table that lists some special characters.

We stock up on a heavy arsenal of methods and properties

The language developers provided many methods and properties to simplify and optimize working with strings. And with the release of a new standard called ES-2015 last year, this list was replenished with new tools.

Length

I'll start with the most popular property, which helps to find out the length of the values ​​of string variables. This length. It is used this way:

var string = "Unicorns";

alert(string.length);

The answer will display the number 9. Also this property can be applied to the values ​​themselves:

"Unicorns".length;

The result will not change.

charAt()

This method allows you to extract a specific character from text. Let me remind you that numbering starts from zero, so to extract the first character from a string, you need to write the following commands:

var string = "Unicorns";

alert(string.charAt(0));.

However, the resulting result will not be a character type; it will still be considered a single-letter string.

From toLowerCase() to UpperCase()

These methods control the case of characters. When writing the code "Content".

toUpperCase() the entire word will be displayed in capital letters.

For the opposite effect, you should use “Content”. toLowerCase().

indexOf()

A popular and necessary tool for searching for substrings. As an argument, you need to enter the word or phrase that you want to find, and the method returns the position of the found element. If the searched text was not found, “-1” will be returned to the user.

1 2 3 4 var text = "Organize a flower search!"; alert(text.indexOf("color")); //19 alert(text.indexOf(" ")); //12 alert(text.lastIndexOf(" ")); //18

var text = "Organize a flower search!"; alert(text.indexOf("color")); //19 alert(text.indexOf(" ")); //12 alert(text.lastIndexOf(" ")); //18

Note that lastIndexOf() does the same thing, only it searches from the end of the sentence.

Substring extraction

For this action, three approximately identical methods were created in js.

Let's look at it first substring (start, end) And slice (start, end). They work the same. The first argument defines the starting position from which the extraction will begin, and the second is responsible for the final stopping point. In both methods, the string is extracted without including the character that is located at the end position.

var text = "Atmosphere"; alert(text.substring(4)); // will display “sphere” alert(text.substring(2, 5)); //display "mos" alert(text.slice(2, 5)); //display "mos"

Now let's look at the third method, which is called substr(). It also needs to include 2 arguments: start And length.

The first specifies the starting position, and the second specifies the number of characters to be extracted. To trace the differences between these three tools, I used the previous example.

var text = "Atmosphere";

alert(text.substr(2, 5)); //display "mosfe"

Using the listed means of taking substrings, you can remove unnecessary characters from new inline elements, with which the program then works.

Reply()

This method helps replace characters and substrings in text. It can also be used to implement global replacements, but to do this you need to include regular expressions.

This example will replace the substring in the first word only.

var text = "Atmosphere Atmosphere"; var newText = text.replace("Atmo","Strato") alert(newText) // Result: Stratosphere Atmosphere

And in this software implementation, because of the flag regular expression“g” will be replaced globally.

var text = "Atmosphere Atmosphere"; var newText = text.replace(/Atmo/g,"Strato") alert(newText) // Result: Stratosphere Stratosphere

Let's do the conversion

JavaScript provides only three types of object type conversion:

  1. Numeric;
  2. String;
  3. Boolean.

In the current publication I will talk about 2 of them, since knowledge about them is more necessary for working with strings.

Numeric conversion

To explicitly convert an element's value to a numeric form, you can use Number (value).

There is also a shorter expression: +"999".

var a = Number("999");

String conversion

Executed by the function alert, as well as an explicit call String(text).

1 2 3 alert (999+ "super price") var text = String(999) alert(text === "999");

alert (999+ "super price") var text = String(999) alert(text === "999");

On this note, I decided to finish my work. Subscribe to my blog and don't forget to share the link to it with your friends. I wish you good luck in your studies. Bye bye!

Best regards, Roman Chueshov

Read: 130 times