Task . Search and replace

Task. Given a string "aaa@bbb@ccc". Replace everything @ on "!" by using global search and replace.

Solution: in this case, you need to use the replace method, which performs a search and replace. However, in a simple use case, this method will find and replace only the first match:

Var str = "aaa@bbb@ccc"; alert(str.replace("@", "!")); //get "aaa!bbb@ccc"

To replace all matches, we use global search using regular expression :

Var str = "aaa@bbb@ccc"; alert(str.replace(/@/g, "!")); //get "aaa!bbb!ccc"

Task . Methods substr, substring, slice

Task. Given a string "aaa bbb ccc". Cut a word out of it "bbb" three in different ways(via substr, substring, slice).

Solution: word "bbb" starts with character number 4 (numbering from zero), and ends with character number 6. Let's use the indicated methods:

Var str = "aaa bbb ccc"; alert(str.substr(4, 3)); //substr(where to cut, how much to cut) alert(str.substring(4, 7)); //substring(from where to cut, to where to cut) alert(str.slice(4, 7)); //slice(where to cut from, where to cut to)

Please note that in the methods substring And slice the second parameter must be 1 greater than the character that we want to remove (that is, if we specify the number 7, then the cutting will occur up to the 6th character inclusive).

Task . Date format conversion

Task. In variable date the date is in the format "2025-12-31" "31/12/2025" .

Solution: using the split method we will split our string "2025-12-31" to array by separator "-" , in this case the zero element will contain the year, the first - the month, and the second - the day:

Var str = "2025-12-31"; var arr = split("-"); alert(arr);//get the array ["2025", "12", "31"]

Now, referring to different elements of the array by their keys, we will form the string we need:

Var str = "2025-12-31"; var arr = split("-"); var newStr = arr + "/" + arr + "/"+arr; alert(newStr); //get the string "12/31/2025"

Problems to solve

Working with character case

Given a string "js". Make it a string "JS".

Given a string "JS". Make it a string "js".

Working with length, substr, substring, slice. Working with indexOf

Given a string "I'm learning javascript!". Find number of characters in this line.

Given a string "I'm learning javascript!". Find the position of the substring "I'm teaching".

Given a variable str, which stores some text. Implement trimming of long text according to the following principle: if the number of characters of this text is greater than specified in the variable n, then into the variable result let's write down the first ones n characters of the string str and add an ellipsis "..." at the end. Otherwise, into a variable result write the contents of the variable str.

Working with replace

Given a string "I'm-learning-javascript!". Replace everything hyphens on "!" by using global search and replace.

Working with split

Given a string "I'm learning javascript!". Using the method split write each word of this line in separate array element.

Given a string "I'm learning javascript!". Using the method split write each character of this string into a separate array element.

In variable date the date is in the format "2025-12-31" . Convert this date to format "31.12.2025" .

Working with join

Given an array ["I", "teach", "javascript", "!"]. Using the method join convert array to string "I'm+learning+javascript+!".

Tasks

Convert first letter strings to uppercase.

Convert the first letter every word strings to uppercase.

Convert String "var_test_text" V "varTestText". The script, of course, should work with any similar strings.

Some videos may get ahead of themselves, as we haven’t covered all of ES6 yet at this point in the tutorial. Just skip these videos and watch them later.

Data type string used to represent text. Accordingly, values ​​of type string are text. Any text in JavaScript is a string.

Quotes

Strings in JavaScript must be enclosed in quotes. There are three types of quotes in JavaScript: double quotes (" "), single quotes (" "), and backticks (` `):

"String in double quotes" "String in single quotes" `String in backquotes`

The type of quotes at the beginning and end of the line must match.

Strings can consist of zero or more characters:

"" // Empty string "String" // Not empty string

Strings with double and single quotes are no different in functionality - they can only contain text and escape sequences. But strings with backquotes have wider functionality. Such lines may contain so-called substitutions, denoted by a dollar sign and curly braces$(expression) . Substitutions can contain any arbitrary expressions:

Let str = "Peace!"; let str2 = `Hello $(str)`; // Using a variable in the line alert(page2); // Hello World! alert(`2 + 3 = $(2 + 3).`); // 2 + 3 = 5.

The expression in the substitution ($(...)) is evaluated and its result becomes part of the string.

Backquoted strings can span more than one line, preserving all whitespace characters:

Let numbers = `Numbers: 1 2`; alert(numbers); // Numbers: // 1 // 2

Strings with backticks are called template strings or template literals.

Strings enclosed in one quotation mark may contain other quotation marks:

"single quotes and backticks inside double quotes" "and here there's 'so' and 'so'!" `and here “so” and “so”!`

For convenience, large string literals can be split into multiple lines, ending each line except the last with a \ character:

Alert("this is all one \ long \ line"); // it's all one long line alert("it's all one \ long \ line"); // it's all one long line alert(`it's all one \ long \ line`); // it's all one long line

String character encoding

Regardless of what encoding is set for the page, JavaScript always uses UTF-16 encoding for strings.

In JavaScript, a string is an immutable, ordered sequence of 16-bit values, each of which represents a Unicode character. JavaScript uses UTF-16 to represent Unicode characters. Characters include letters, numbers, punctuation, special characters, and whitespace.

String length

String length is the number of 16-bit values ​​(not the characters themselves) contained in it. The length of the string is contained in the length property:

Alert("Hello".length); // 6

Characters whose code points do not fit into 16 bits are processed according to the UTF-16 encoding rules as a sequence of two 16-bit values. This means that a string that has a length of 2 (two 16-bit values) can actually represent a single character:

Alert("a".length); // 1 alert("𝑒".length); // 2

Numbering and accessing string characters

As already mentioned, a string is an ordered sequence of 16-bit values, each of which corresponds to a specific character. The numbering of 16-bit values ​​in a string starts from zero, i.e. the first 16-bit value is at index 0, the second at index 1, etc. The index is a sequence number.

You can get a string character (consisting of a single 16-bit value) using the index enclosed in square brackets[index] :

Let str = "Hello"; alert(str); // P alert(str); // IN

To use indices to refer to a character consisting of two 16-bit values, you need to use concatenation to write these indices so that the result is a sequence of two 16-bit values:

Let str = "𝑒"; alert(page + page); // "𝑒"

Strings are immutable

In JavaScript, strings are immutable. This means that you cannot change any characters in an existing string or add anything new to it.

Since strings are immutable, methods used to work with strings return new strings rather than modifying the string on which they were called:

Let str = "Hello!"; alert(str.toUpperCase()); // "HELLO" - new value returned by the method alert(page); // "hello" - the original line is not changed

To change a string, you can create a new string and write it to the same variable instead of the old string:

Let str = "String"; str = str.toUpperCase(); alert(str); // "LINE"

Escape Sequences

You can use escape sequences in string literals. Control sequence is a sequence of ordinary characters that represents a character that is not otherwise representable within a string. Escape sequences are used to format the output of text content.

The table below shows the control sequences:

Subsequence Meaning
\0 The NUL character is the empty character ("\u0000").
\t Horizontal tab ("\u0009").
\n Newline ("\u000A").
\b Going back one position is what happens when you press the backspace key ("\u0008").
\r Carriage return ("\u000D").
\f Page translation - page clearing ("\u000C").
\v Vertical tab ("\u000B").
\" Double quote ("\u0022").
\" Single quote ("\u0027").
\\ Backslash ("\u005C").
\xNN The number of a character from the ISO Latin-1 character set, specified by two hexadecimal digits (N is hexadecimal digit 0-F). For example, "\x41" (this is the code for the letter "A").
\uNNNN The number of a character from the Unicode character set, specified by four hexadecimal digits (N is hexadecimal digit 0-F). For example, "\u0041" (this is the code for the letter "A"s).

Escape sequences can appear anywhere on a line:

Alert("Greek letter sigma: \u03a3."); // Greek letter sigma: Σ. alert("Multiline string") // Multiline string alert("double quotes are used inside"); // double quotes are used inside

If the \ character precedes any character other than those given in the table, then it is simply ignored by the interpreter:

Alert("\k"); // "k"

Unicode characters specified using an escape sequence can be used not only inside string literals, but also in identifiers:

Let a\u03a3 = 5; alert(a\u03a3); // 5

Concatenation

Concatenation is the concatenation of two or more strings into one larger one. Concatenation occurs using the + (plus) operator. When concatenating, each subsequent line is added to the end of the previous one:

Var str1 = "Hello"; var str2 = "World!"; document.write(str1 + str2 + "
"); // "Hello World!" document.write(str1 + "World!"); Try »

A value of any type that is concatenated with a string will be implicitly (automatically) converted to a string and then concatenated.

Var str1 = "Hello"; alert(str1 + 1); // "Hello 1" alert(true + str1); // "trueHello" alert(str1 + NaN); // "Hello NaN"

There are several ways to select substrings in JavaScript, including substring(), substr(), slice() and functions regexp.

In JavaScript 1.0 and 1.1, substring() exists as the only simple way to select part of a larger string. For example, to select the line press from Expression, use "Expression".substring(2,7). The first parameter to the function is the character index at which the selection begins, while the second parameter is the character index at which the selection ends (not including): substring(2,7) includes indexes 2, 3, 4, 5, and 6.

In JavaScript 1.2, functions substr(), slice() And regexp can also be used to split strings.

Substr() behaves in the same way as substr the Pearl language, where the first parameter indicates the character index at which the selection begins, while the second parameter specifies the length of the substring. To perform the same task as in the previous example, you need to use "Expression".substr(2,5). Remember, 2 is the starting point, and 5 is the length of the resulting substring.

When used on strings, slice() behaves similarly to the function substring(). It is, however, much more powerful, capable of working with any type of array, not just strings. slice() also uses negative offsets to access the desired position, starting from the end of the line. "Expression".slice(2,-3) will return the substring found between the second character and the third character from the end, returning press again.

The last and most universal method for working with substrings is working through regular expression functions in JavaScript 1.2. Once again, paying attention to the same example, the substring "press" obtained from the string "Expression":

Write("Expression".match(/press/));

Built-in object String

Object String This is an object implementation of a primitive string value. Its constructor looks like:

New String( meaning?)

Here meaning any string expression that specifies the primitive value of an object. If not specified, the object's primitive value is "" .

Properties of the String object:

constructor The constructor that created the object. Number of characters per line. prototype A reference to the object class prototype.

Standard String Object Methods

Returns the character at the given position in the string. Returns the code of the character located at a given position in the string. Returns a concatenation of strings. Creates a string from characters specified by Unicode codes. Returns the position of the first occurrence of the specified substring. Returns the position of the last occurrence of the specified substring. Compares two strings based on language operating system. Matches a string against a regular expression. Matches a string against a regular expression and replaces the found substring with a new substring. Matches a string with a regular expression. Retrieves part of a string and returns a new string. Splits a string into an array of substrings. Returns a substring given by position and length. Returns a substring specified by the starting and ending positions. Converts all letters of a string to lowercase, taking into account the operating system language. Converts all letters in a string to uppercase based on the operating system language. Converts all letters in a string to lowercase. Converts an object to a string. Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object

Creates an HTML bookmark ( …). Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags …. Creates HTML hyperlink(). Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags …. Wraps a string in tags ….

length property

Syntax : object.length Attributes: (DontEnum, DontDelete, ReadOnly)

Property value length is the number of characters in the line. For an empty string this value is zero.

anchor method

Syntax : object.anchor( Name) Arguments: Name Result: string value

Method anchor object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to create a bookmark in an HTML document with the specified name. For example, the operator document.write("My text".anchor("Bookmark")) is equivalent to the operator document.write(" My text") .

big method

Syntax : object.big() Result: string value

Method big returns a string consisting of object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in large font. For example, the statement document.write("My text".big()) will display the string My text on the browser screen.

blink method

Syntax : object.blink() Result: string value

Method blink returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in blinking font. These tags are not part of the HTML standard and are only supported by Netscape and WebTV browsers. For example, the statement document.write("My text".blink()) will display the string My text on the browser screen.

bold method

Syntax : object.bold() Result: string value

Method bold returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in bold font. For example, the operator document.write("My text".bold()) will display the line My text .

charAt method

Syntax : object.charAt( position) Arguments: position any numeric expression Result: string value

Method charAt returns a string consisting of the character located in the given positions primitive string value object. Line character positions are numbered from zero to object. -1. If the position is outside this range, an empty string is returned. For example, the statement document.write("String".charAt(0)) will print the character C to the browser screen.

charCodeAt method

Syntax : object.charCodeAt( position) Arguments: position any numeric expression Result: numeric value

Method charAt returns a number equal to the Unicode code of the character located in the given positions primitive string value object. Line character positions are numbered from zero to object. -1. If the position is outside this range, it returns NaN. For example, the operator document.write("String".charCodeAt(0).toString(16)) will display the hexadecimal code of the Russian letter "C" on the browser screen: 421.

concat method

Syntax : object.concat( line0, line1, …, stringN) Arguments: line0, line1, …, stringN any string expressions Result: string value

Method concat returns a new string that is the concatenation of the original string and the method arguments. This method is equivalent to the operation

object + line0 + line1 + … + stringN

For example, the operator document.write("Frost and sun.".concat("Wonderful day.")) will display the line Frost and sun on the browser screen. It's a wonderful day.

fixed method

Syntax : object.fixed() Result: string value

Method fixed returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in a teletype font. For example, the statement document.write("My text".fixed()) will display the string My text on the browser screen.

fontcolor method

Syntax : object.fontcolor(color) Arguments: color string expression Result: string value

Method fontcolor returns a string consisting of a primitive string value object, enclosed in tags color>…. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in a specified color. For example, the statement document.write("My text".fontcolor("red")) will display the string My text on the browser screen.

fontsize method

Syntax : object.fontsize( size) Arguments: size numeric expression Result: string value

Method fontsize returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in a specified font size. For example, the statement document.write("My text".fontsize(5)) will display the string My text on the browser screen.

fromCharCode method

Syntax : String.fromCharCode( code1, code2, …, codeN) Arguments: code1, code2, …, codeN numeric expressions Result: string value

Method fromCharCode creates a new string (but not a string object) that is the concatenation of Unicode characters with codes code1, code2, …, codeN.

This is a static method of an object String, so you don't need to specifically create a string object to access it. Example:

Var s = String.fromCharCode(65, 66, 67); // s equals "ABC"

indexOf method

Syntax : object.indexOf( substring[,start]?) Arguments: substring any string expression start any numeric expression Result: numeric value

Method indexOf returns first position substrings in the primitive string value object. object start start start start more than object object

The search is carried out from left to right. Otherwise, this method is identical to the method. The following example counts the number of occurrences of the substring pattern in the string str .

Function occur(str, pattern) ( var pos = str.indexOf(pattern); for (var count = 0; pos != -1; count++) pos = str.indexOf(pattern, pos + pattern.length); return count ; )

Italics method

Syntax : object.italics() Result: string value

Method italics returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in italic font. For example, the operator document.write("My text".italics()) will display the line My text .

lastIndexOf method

Syntax : object.lastIndexOf( substring[,start]?) Arguments: substring any string expression start any numeric expression Result: numeric value

Method lastIndexOf returns last position substrings in the primitive string value object object. -1. If an optional argument is given start, then the search is carried out starting from the position start; if not, then from position 0, i.e. from the first character of the line. If start negative, then it is taken equal to zero; If start more than object. -1, then it is taken equal object. -1. If the object does not contain this substring, then the value -1 is returned.

The search is carried out from right to left. Otherwise, this method is identical to the method. Example:

Var n = "White whale".lastIndexOf("whale"); // n equals 6

link method

Syntax : object.link( uri) Arguments: uri any string expression Result: string value

Method link returns a string consisting of a primitive string value object, enclosed in uri tags"> . There is no check to see if the source string was already enclosed within these tags. This method is used in conjunction with the document.write and document.writeln methods to create a hyperlink in an HTML document with the specified uri. For example, the statement document.write("My Text".link("#Bookmark")) is equivalent to the statement document.write("My Text") .

localeCompare method

Syntax : object.localeCompare( line1) Arguments: line1 any string expression Result: number

Support

Method localeCompare compares two strings taking into account the national settings of the operating system. It returns -1 if primitive value object less lines1, +1 if it is greater lines1, and 0 if these values ​​are the same.

match method

Syntax : object.match( Regvyr) Arguments: Regvyr Result: array of strings

Method match Regvyr object. The result of the match is an array of found substrings or null, if there are no matches. In this case:

  • If Regvyr does not contain a global search option, then the method is executed Regvyr.exec(object) and its result is returned. The resulting array contains the found substring in the element with index 0, and the remaining elements contain substrings corresponding to the subexpressions Regvyr, enclosed in parentheses.
  • If Regvyr contains a global search option, then the method Regvyr.exec(object) is executed as long as matches are found. If n is the number of matches found, then the result is an array of n elements that contain the found substrings. Property Regvyr.lastIndex assigned a position number in the source string pointing to the first character after the last match found, or 0 if no matches were found.

It should be remembered that the method Regvyr.exec changes object properties Regvyr. Examples:

replace method

Syntax : object.replace( Regvyr,line) object.replace( Regvyr,function) Arguments: Regvyr regular expression string string expression function function name or function declaration Result: new line

Method replace matches regular expression Regvyr with a primitive string value object and replaces the found substrings with other substrings. The result is a new string, which is a copy of the original string with the replacements made. The replacement method is determined by the global search option in Regvyr and the type of the second argument.

If Regvyr does not contain a global search option, then the search is performed for the first substring that matches Regvyr and it is replaced. If Regvyr contains a global search option, then all substrings matching Regvyr, and they are replaced.

line, then each found substring is replaced with it. In this case, the line may contain the following object properties RegExp, like $1 , , $9 , lastMatch , lastParen , leftContext and rightContext . For example, the operator document.write("Delicious apples, juicy apples.".replace(/apples/g, "pears")) will display the line Delicious pears, juicy pears on the browser screen.

If the second argument is function, then each substring found is replaced by calling this function. The function has the following arguments. The first argument is the found substring, followed by arguments matching all subexpressions Regvyr, enclosed in parentheses, the penultimate argument is the position of the found substring in the source string, counting from zero, and the last argument is the source string itself. The following example shows how to use the method replace you can write a function to convert Fahrenheit to Celsius. The given scenario

Function myfunc($0,$1) ( return (($1-32) * 5 / 9) + "C"; ) function f2c(x) ( var s = String(x); return s.replace(/(\d+( \.\d*)?)F\b/, myfunc); ) document.write(f2c("212F"));

will display the line 100C on the browser screen.

Please note that this method changes the properties of the object Regvyr.

Replace example

Replacing all occurrences of a substring in a string

It often happens that you need to replace all occurrences of one string with another string:

Var str = "foobarfoobar"; str=str.replace(/foo/g,"xxx"); // the result will be str = "xxxbarxxxbar";

search method

Syntax : object.search( Regvyr) Arguments: Regvyr any regular expression Result: numeric expression

Method search matches regular expression Regvyr with a primitive string value object. The result of the match is the position of the first substring found, counting from zero, or -1 if there are no matches. At the same time, the global search option in Regvyr is ignored, and properties Regvyr do not change. Examples:

slice method

Syntax : object.slice( start [,end]?) Arguments: start And end any numerical expressions Result: new line

Method slice object, from position start to position end, without including it. If end start and until the end of the original line.

Line character positions are numbered from zero to object. -1. If the value start object. +start. If the value end negative, then it is replaced by object. +end. In other words, negative arguments are treated as offsets from the end of the string.

The result is a string value, not a string object. For example, the statement document.write("ABCDEF".slice(2,-1)) will print the string CDE to the browser screen.

small method

Syntax : object.small() Result: string value

Method small returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in small font. For example, the statement document.write("My text".small()) will display the string My text on the browser screen.

split method

Syntax : object.split( separator [,number]?) Arguments: separator string or regular expression number numeric expression Result: string array(object Array)

Method split breaks the primitive value object to an array of substrings and returns it. The division into substrings is done as follows. The source string is scanned from left to right looking for delimiter. Once it is found, the substring from the end of the previous delimiter (or from the beginning of the line if this is the first occurrence of the delimiter) to the beginning of the one found is added to the substring array. Thus, the separator itself does not appear in the text of the substring.

Optional argument number specifies the maximum possible size of the resulting array. If it is specified, then after selection numbers The substring method exits even if the scan of the original string is not finished.

Separator can be specified either as a string or as a regular expression. There are several cases that require special consideration:

The following example uses a regular expression to specify HTML tags as a delimiter. Operator

will display the line Text, bold, and italic on the browser screen.

strike method

Syntax : object.strike() Result: string value

Method strike returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text in a strikethrough font. For example, the statement document.write("My text".strike()) will display the string My text on the browser screen.

sub method

Syntax : object.sub() Result: string value

Method sub returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text as a subscript. For example, the statement document.write("My text".sub()) will display the string My text on the browser screen.

substr method

Syntax : object.substr( position [,length]?) Arguments: position And length numeric expressions Result: string value

Method substr returns a substring of the primitive value of a string object starting with this positions and containing length characters. If length is not specified, then a substring is returned starting from the given one positions and until the end of the original line. If length is negative or zero, an empty string is returned.

Line character positions are numbered from zero to object. -1. If position greater than or equal to object., then an empty string is returned. If position is negative, then it is interpreted as an offset from the end of the line, i.e., it is replaced by object.+position.

Note. If position is negative, then Internet Explorer mistakenly replaces it with 0, so for compatibility reasons this option should not be used.

Var src = "abcdef"; var s1 = src.substr(1, 3); // "bcd" var s2 = src.substr(1); // "bcdef" var s3 = src.substr(-1); // "f", but in MSIE: "abcdef"

substring method

Syntax : object.substring( start [,end]) Arguments: start And end numeric expressions Result: string value

Method substring returns a substring of the primitive value of a string object, from position start to position end, without including it. If end is not specified, then a substring is returned, starting from position start and until the end of the original line.

Line character positions are numbered from zero to object. -1. Negative arguments or equal NaN are replaced by zero; if the argument is greater than the length of the original string, then it is replaced with it. If start more end, then they change places. If start equals end, then an empty string is returned.

The result is a string value, not a string object. Examples:

Var src = "abcdef"; var s1 = src.substring(1, 3); // "bc" var s2 = src.substring(1, -1); // "a" var s3 = src.substring(-1, 1); // "a"

sup method

Syntax : object.sup() Result: string value

Method sup returns a string consisting of a primitive string value object, enclosed in tags …. There is no check to see if the original string was already enclosed in these tags. This method is used in conjunction with the document.write and document.writeln methods to display text as a superscript. For example, the statement document.write("My text".sup()) will display the string My text on the browser screen.

toLocaleLowerCase Method

Syntax : object.toLocaleLowerCase() Result: new line

Support: Internet Explorer Supported from version 5.5. Netscape Navigator Not supported.

Method toLocaleLowerCase returns a new string in which all letters of the original string are replaced with lowercase ones, taking into account the locale settings of the operating system. The remaining characters of the original string are not changed. The original string remains the same. Typically this method returns the same result as ; the difference is only possible if the language encoding conflicts with the Unicode rules for converting uppercase to lowercase letters.

toLocaleUpperCase Method

Syntax : object.toLocaleUpperCase() Result: new line

Support: Internet Explorer Supported from version 5.5. Netscape Navigator Not supported.

Method toLocaleUpperCase returns a new string in which all letters of the original string are replaced with uppercase, taking into account the locale settings of the operating system. The remaining characters of the original string are not changed. The original string remains the same. Typically this method returns the same result as ; the difference is only possible if the language encoding conflicts with the Unicode rules for converting lowercase letters to uppercase letters.

toLowerCase method

Syntax : object.toLowerCase() Result: new line

Method toLowerCase returns a new string with all letters of the original string replaced with lowercase ones. The remaining characters of the original string are not changed. The original string remains the same. For example, the statement document.write("String object".toLowerCase()) will display the string string object.

Hello everyone and happy new year. Let's 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));

the slice() method returns a substring ("properties"), taking two numeric values ​​as arguments, 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 characters are in uppercase, that is, in capital letters.

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

the toLowerCase() method returns us a string where all 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 wrote down 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!

Greetings to everyone who has thoroughly decided to learn a prototype-oriented language. Last time I told you about , and today we will parse 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.

When initializing variables, values ​​can be framed in doubles, singles, and, starting in 2015, 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).


Close