Javascript functions for working with strings. Tasks on functions of working with strings in JavaScript. Variables with template literals

💖 Do you like it? Share the link with your friends

When I write in javascript, I often need to refer to search engines, in order to clarify the syntax of methods (and order, definition of arguments) working with strings.

In this article I will try to give examples and descriptions of the most common javascript methods related to strings. The most popular methods are located at the top of the article for convenience.

Convert to string

You can convert a number, boolean, or object to a string.

Var myNumber = 24; // 24 var myString = myNumber.toString(); // "24"

You can also perform a similar manipulation using the string() function.

Var myNumber = 24; // 24 var myString = String(myNumber); // "24"

Nicholas Zakas says: "If you are not sure about the value (null or undefined), then use the String() function, since it returns a string regardless of the type of the variable."

undefined means that the variable is not assigned any value, a null, - that it is assigned an empty value (we can say that null is defined as an empty object).

Split a string into substrings

To split a string into an array of substrings you can use the split() method:

Var myString = "coming,apart,at,the,commas"; var substringArray = myString.split(","); // ["coming", "apart", "at", "the", "commas"] var arrayLimited = myString.split(",", 3); // ["coming", "apart", "at"]

As the last line suggests, the value of the second optional argument determines the number of elements in the returned array.

Get string length

Using the length property you can find the number of Unicode characters in a string:

Var myString = "You"re quite a character."; var stringLength = myString.length; // 25

Define a substring in a string

There are two ways to achieve your plan:

Use indexOf() :

Var stringOne = "Johnny Waldo Harrison Waldo"; var wheresWaldo = stringOne.indexOf("Waldo"); // 7

The indexOf() method searches for a substring (the first argument passed) in a string (from the beginning of the string) and returns the position of the first character from which the substring began appearing in the string.

Use lastIndexOf() :

Var stringOne = "Johnny Waldo Harrison Waldo"; var wheresWaldo = stringOne.lastIndexOf("Waldo"); // 22

The lastIndexOf() method does everything the same, except that it looks for the last substring that occurs in the string.

If the substring is not found, both methods return -1. The second optional argument specifies the position in the string where you want to start the search. So, if the second argument to the indexOf() method is 5, then the search will start from the 5th character, and characters 0-4 will be ignored. For lastIndexOf() , also if the second argument is 5, the search will start in the opposite direction, with characters 6th and above being ignored.

How to replace part of a string

To replace part (or even all) of a string, use the replace() method.

Var slugger = "Josh Hamilton"; var betterSlugger = slugger.replace("h Hamilton", "e Bautista"); console.log(betterSlugger); // "Jose Bautista"

The first argument contains the part of the substring that is to be replaced; the second argument is the string that will take the place of the substring being replaced. Only the first instance of the substring will be replaced.

To replace all occurrences of a substring, use a regular expression with the "g" flag.

Var myString = "She sells automotive shells on the automotive shore"; var newString = myString.replace(/automotive/g, "sea"); console.log(newString); // "She sells sea shells on the sea shore"

The second argument may include the substring or function to be replaced.

Find a character at a given position

To find out which character is at a given position, you can use the charAt() method:

Var myString = "Birds of a Feather"; var whatsAtSeven = myString.charAt(7); // "f"

As is often the case in javascript, the first position starts from 0, not 1.

Alternatively, you can use the charCodeAt() method, but instead of the character itself, you will receive its code.

Var myString = "Birds of a Feather"; var whatsAtSeven = myString.charCodeAt(7); // "102" var whatsAtEleven = myString.charCodeAt(11); // "70"

Note that the code for a capital letter (position 11) is different from the code for the same letter in lower case (position 7).

String concatenation in javascript

For the most part, you will use the (+) operator to concatenate strings. But you can also concatenate strings using the concat() method.

Var stringOne = "Knibb High football"; var stringTwo = stringOne.concat("rules."); // "Knibb High football rules"

Multiple strings can be passed to concat(), and the resulting string will appear in the order in which they were added to the concat() method.

Var stringOne = "Knibb"; var stringTwo = "High"; var stringThree = "football"; var stringFour = "rules."; var finalString = stringOne.concat(stringTwo, stringThree, stringFour); console.log(finalString); // "Knibb high football rules."

Part of a string (extract substring in javascript)

There are three different ways create a new string by “pulling out” part of a substring from an existing string.

Using slice() :

Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.slice(5, 10); // "fghij"

Using substring() :

Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.substring(5, 10); // "fghij"

For both (slice() and substring()) methods, the first argument is the position of the character at which the substring begins (counting from 0), the second argument is the position of the character at which the substring ends, and the character designated in the second argument is is not included in the returned substring.

Using substr() :

Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.substr(5, 10); // "fghijklmno"

For the substr method, the first argument also specifies the position of the character at which the substring begins. The second argument is optional. But at the same time, the second argument specifies the number of characters that should be included in the substring, starting from the position that we already defined in the first argument. This technique is well illustrated in the example above.

Converting a string to lower or upper case in javascript

There are four methods to make the necessary conversions. Two to convert string characters to upper case.

Var stringOne = "Speak up, I can"t hear you."; var stringTwo = stringOne.toLocaleUpperCase(); // "SPEAK UP, I CAN"T HEAR YOU" var stringThree = stringOne.toUpperCase(); // "SPEAK UP, I CAN"T HEAR YOU"

And two to convert the string to lowercase:

Var stringOne = "YOU DON"T HAVE TO YELL"; var stringTwo = stringOne.toLocaleLowerCase(); // "you don"t have to yell" var stringThree = stringOne.toLowerCase(); // "you don"t have to yell"

In general, there is no difference between a locale method and a non-locale method, however, "for some languages, such as Turkish, whose character case does not follow the established Unicode case, the consequences of using a non-locale method may be different." Therefore, follow the following rule: "if you do not know the language in which the code will run, it is safer to use locale methods."

Pattern matching in javascript

You can check for the presence of a pattern in a string using 2 methods.

The match() method is called on a string object, passing a regular expression as an argument to the match() method.

Var myString = "How much wood could a wood chuck chuck"; var myPattern = /.ood/; var myResult = myString.match(myPattern); // ["wood"] var patternLocation = myResult.index; // 9 var originalString = myResult.input // "How much wood could a wood chuck chuck"

And the exec() method is called on the RegExp object, passing the string as an argument:

Var myString = "How much wood could a wood chuck chuck"; var myPattern = /.huck/; var myResult = myPattern.exec(myString); // ["chuck"] var patternLocation = myResult.index; // 27 var originalString = myResult.input // "How much wood could a wood chuck chuck"

Both methods return the first occurrence that matches. If no matches are found, NULL will be returned. If regular expression If the "g" flag is present, the result will be an array containing all matches.

You can also use the search() method, which takes a regular expression as an argument and returns the starting position of the first matched pattern.

Var myString = "Assume"; var patternLocation = myString.search(/ume/); // 3

If no matches are found, the method will return -1.

Comparing two strings for later sorting

To compare two strings based on the locale's sort order, you can use the localeCompare method. The localeCompare method returns three possible values.

MyString = "chicken"; var myStringTwo = "egg"; var whichCameFirst = myString.localeCompare(myStringTwo); // -1 (except Chrome, which returns -2) whichCameFirst = myString.localeCompare("chicken"); // 0 whichCameFirst = myString.localeCompare("apple"); // 1 (Chrome returns 2)

As shown above, will be returned negative meaning, if the original string comes before the string argument when sorted, if the string argument comes after the original string when sorted, the value +1 is returned. If null is returned, the two strings are equivalent.

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

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, 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 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

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 in JavaScript work with strings can be "taken outside" 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 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 symbols and strings require increased attention to locale, especially when you need to work with Cyrillic. In many cases it is advisable to indicate real codes symbols 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 best quality code with greater reliability of the developed algorithm.

When you write JavaScript, very often you have to surf the Internet in search of information about the syntax and parameters for methods that work with strings.

I've read a lot of articles on working with strings. This post will show examples and brief descriptions the most common methods for working with strings. I've tried to put the most common methods at the top for quick reference.

Of course, most experienced developers will already be fairly familiar with many of the techniques, but I think this is a good list for beginners to understand the range of techniques that can help accomplish complex operations with simple means.

Converting to String

You can convert a number, boolean expression, or object to a string:

Var myNumber = 24; // 24 var myString = myNumber.toString(); // "24"

You can do it the same way with String():

Var myNumber = 24; // 24 var myString = String(myNumber); // "24"

If you are not sure what the value is not null or undefined, you can use String(), which always returns a string, regardless of the value type.

Splitting a string into substrings

To split strings into an array of substrings you can use the method split():

Var myString = "coming,apart,at,the,commas"; var substringArray = myString.split(","); // ["coming", "apart", "at", "the", "commas"] var arrayLimited = myString.split(",", 3); // ["coming", "apart", "at"]

As seen in last line, the second parameter of the function is the limit on the number of elements that will be in the final array.

Getting the length of a string

To find how many characters there are in a string, we use the property length:

Var myString = "You"re quite a character."; var stringLength = myString.length; // 25

Finding a substring in a string

There are two methods to search for a substring:

Usage indexOf():

Var stringOne = "Johnny Waldo Harrison Waldo"; var wheresWaldo = stringOne.indexOf("Waldo"); // 7

indexOf() The method starts searching for a substring from the beginning of the string, and returns the position of the beginning of the first occurrence of the substring. In this case - 7th position.

Usage lastIndexOf():

Var stringOne = "Johnny Waldo Harrison Waldo"; var wheresWaldo = stringOne.lastIndexOf("Waldo"); // 22

The method returns the starting position of the last occurrence of a substring in a string.

Both methods return -1 if the substring is not found, and both take an optional second argument indicating the position in the string where you want the search to begin. So if the second argument is "5", indexOf() starts the search from character 5, ignoring characters 0-4, while lastIndexOf() starts the search at character 5 and works backwards, ignoring characters 6 and beyond.

Substring replacement

To replace an occurrence of a substring in a string with another substring, you can use replace():

Var slugger = "Josh Hamilton"; var betterSlugger = slugger.replace("h Hamilton", "e Bautista"); console.log(betterSlugger); // "Jose Bautista"

The first argument is what you want to replace and the second argument is the newline. The function replaces only the first occurrence of a substring in a string.

To replace all occurrences, you need to use a regular expression with a global flag:

Var myString = "She sells automotive shells on the automotive shore"; var newString = myString.replace(/automotive/g, "sea"); console.log(newString); // "She sells sea shells on the sea shore"

The second argument may include a special template or function. You can read more.

Get a character at a given position in a string

We can get the symbol using the function charAt():

Var myString = "Birds of a Feather"; var whatsAtSeven = myString.charAt(7); // "f"

As is often the case in JavaScript, the first position in the string starts at 0, not 1.

As an alternative function you can use charCodeAt() function, which is the character code.

Var myString = "Birds of a Feather"; var whatsAtSeven = myString.charCodeAt(7); // "102" var whatsAtEleven = myString.charCodeAt(11); // "70"

Note that the code for the "F" character (position 11) is different than the "f" character (position 7).

Concatenating Strings

In most cases, you can use the "+" operator to concatenate strings. But you can also use the method concat():

Var stringOne = "Knibb High football"; var stringTwo = stringOne.concat("rules."); // "Knibb High football rules"

In this way we can combine many lines into one in the order in which they are written:

Var stringOne = "Knibb"; var stringTwo = "High"; var stringThree = "football"; var stringFour = "rules."; var finalString = stringOne.concat(stringTwo, stringThree, stringFour); console.log(finalString); // "Knibb high football rules."

Substring extraction

There are 3 ways to get a string from part of another string:

Using slice():

Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.slice(5, 10); // "fghij"

Using substring():

Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.substring(5, 10); // "fghij"

In both functions, the first parameter is the character at which the substring begins (starting from position 0) and the second argument (optional) is the position of the character up to which the substring is returned. The example (5, 10) returns the string between positions 5 and 9.

Using substr():

Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.substr(5, 10); // "fghijklmno"

The first argument is the position of the character at which the new line begins and the second argument is the number of characters from the starting position of the new line. Those. (5, 10) returns 10 characters, starting at position 5.

Convert a string to upper or lower case.

There are 4 methods for translation. The first 2 convert the string to uppercase:

Var stringOne = "Speak up, I can"t hear you."; var stringTwo = stringOne.toLocaleUpperCase(); // "SPEAK UP, I CAN"T HEAR YOU" var stringThree = stringOne.toUpperCase(); // "SPEAK UP, I CAN"T HEAR YOU"

The other 2 convert the string to lower case:

Var stringOne = "YOU DON"T HAVE TO YELL"; var stringTwo = stringOne.toLocaleLowerCase(); // "you don"t have to yell" var stringThree = stringOne.toLowerCase(); // "you don"t have to yell"

It's better to use "locale" methods, because... in different places, for example, in Turkey, the display of registers does not work quite the way we are used to and therefore the result may be the one we wanted. If you use “locale” methods, then there will be no such problems.

Pattern Matching

Pattern matching on a string can be done using 2 methods, which work differently.

Method match() is applied to a string and it takes a regular expression as a parameter:

Var myString = "How much wood could a wood chuck chuck"; var myPattern = /.ood/; var myResult = myString.match(myPattern); // ["wood"] var patternLocation = myResult.index; // 9 var originalString = myResult.input // "How much wood could a wood chuck chuck"

Method exec() applied to a regular expression object and takes the string as a parameter:

Var myString = "How much wood could a wood chuck chuck"; var myPattern = /.huck/; var myResult = myPattern.exec(myString); // ["chuck"] var patternLocation = myResult.index; // 27 var originalString = myResult.input // "How much wood could a wood chuck chuck"

In both methods, only the first match is returned. If there are no matches, it returns null.

You can also use the method search() which takes a regular expression and returns the position of the first match in the pattern:

Var myString = "Assume"; var patternLocation = myString.search(/ume/); // 3

If there were no matches, “ -1 «.

Comparing two strings for sorting

You can compare 2 strings to determine which comes first in the alphabet. To do this, we will use the method localeCompare() which returns 3 possible values:

Var myString = "chicken"; var myStringTwo = "egg"; var whichCameFirst = myString.localeCompare(myStringTwo); // -1 (Chrome returns -2) whichCameFirst = myString.localeCompare("chicken"); // 0 whichCameFirst = myString.localeCompare("apple"); // 1 (Chrome returns 2)

As shown above, a negative number is returned if the string argument comes after the original string. Positive number, if the string argument comes before the original string. If returned 0 - means the lines are equal.

To check the return value it is better to use if (result< 0), чем if (result === -1). Последнее не будет работать в Chrome.

Thank you for your attention, I hope that you learned a lot of new and interesting things!

Author of the article: Alex. Category:
Date of publication: 03/19/2013

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 that this section occupies a 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. This property can also 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 line 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 Due to the regular expression flag “g”, a global replacement will be performed.

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).

Hello everyone and happy new year. Go! We'll start by looking at the length property, which allows us to count the number of characters in a string:

Var str = "methods and properties for working with strings in javaScript"; console.log(str.length);

As you can see, the console displays the result, the number of characters in the line (54).

Var str = "methods and properties for working with strings in javaScript"; console.log(str.charAt(7));

Using the charAt() method, we can get a string character at a given position; in our case, we get the “and” character at the 7th position. Note that the line position report starts from zero. For example, if we want to get the first character of a string:

Var str = "methods and properties for working with strings in javaScript"; str.charAt(0);

here we will get back "m". There is also a similar method charCodeAt() IT WORKS EXACTLY AS charAt(), but it returns not the character itself, but its code.

Var str = "methods and properties for working with strings in javaScript"; console.log(str.charCodeAt(0));

The code for the character "m" (1084) will be returned to us.

The charAt() method is useful for extracting a single character from a string, but if we want to get a set of characters (substring), then the following methods are suitable for this purpose:

Var str = "methods and properties for working with strings in javaScript"; console.log(str.slice(8,17));

slice method() returns a substring ("properties"), taking as arguments two numeric values, the starting and ending index of the substring. Another similar method is substr():

Var str = "methods and properties for working with strings in javaScript"; console.log(str.substr(8,17));

here we will get back a substring (“properties for slave”), the first argument is the starting position, and the second is the number of characters in the substring. Next we will look at methods for working with case in strings.

Var str = "methods and properties for working with strings in javaScript"; console.log(str.toUpperCase());

the toUpperCase() method returns us a string where all the characters in uppercase, that is, in capital letters.

Var str = "MBA"; console.log(str.toLowerCase());

the toLowerCase() method returns us a string where all the characters are lowercase, small letters.

To find a substring in a string, we can use the indexOf() method:

Var str = "methods and properties for working with strings in javaScript"; document.write(str.indexOf("works"));

this method takes as an argument the substring we want to find in the string and if it finds it, then the position at which the match was found is returned. If this substring is not contained in the string, then:

Var str = "methods and properties for working with strings in javaScript"; document.write(str.indexOf("work"));

we will get the value -1. Example:

Var str = "methods and properties for working with strings in javaScript", sub = "work"; function indexOf(str, substr) ( if (str.indexOf(substr) === -1) ( return "This substring ""+substr+"" is not contained in the string ""+str+"""; ) else( index = str.indexOf(substr) return "Substring ""+substr+"" found at position "+index; ) ) document.write(indexOf(str,sub));

Here we have written a small function indexOf(str,sub) which takes a string(str) and a substring(sub) as arguments and, using the indexOf() method, checks for the presence of a substring in the string and returns a message about the result. I note that the indexOf() method returns the position of the substring relative to the beginning of the string, that is, from index zero.

If we want to find the position of a substring relative to the end, then we can use the lastIndexOf() function.

The trim() method allows you to remove spaces from the beginning and end of a string, let's say we have the following string:

Var str = "methods and properties for working with strings in javaScript"; console.log(str);

and we want to remove spaces at the beginning and end:

Console.log(str.trim());

after we use the trim() method, the spaces from the end and beginning of the string will be successfully removed.

Well, that’s basically all I wanted to tell you about working with strings in JavaScript. Of course, there are also methods for concatenating and comparing strings, but we won’t consider them, since these methods are easily replaced by standard operators.

I congratulate you on the upcoming New Year, I wish you happiness, health, success, love and of course good luck! Bye!



tell friends