JavaScript: methods for working with strings. Tasks on functions for working with strings in JavaScript Jquery functions for working with strings

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

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

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

Creating and viewing a string

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

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

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

The third and newest way to create a string is called a template literal. Template literals are written inside backquotes (also known as backticks) and work just like regular strings, with a few extra features that we'll cover in this article.

`This string uses backticks.`;

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

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

Another simple way to query the value of a string is through a browser popup, which can be invoked using alert():

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

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

This is a string in an alert.

The alert() method is used less frequently because alerts need to be closed constantly.

Storing strings in variables

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

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

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

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

By assigning strings to variables, you don't have to retype the string each time you want to output it, making it easier to work with strings within programs.

String concatenation

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

For example, try concatenating two short strings:

"Sea" + "horse";
Seahorse

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

"Sea" + "horse";
Sea horse

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



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

The new strings resulting from concatenation can be used in the program.

Variables with template literals

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

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

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

String literals and string values

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

"Beyond the Sea";
Beyond the Sea

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

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

Traversing quotes and apostrophes in strings

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

Consider this example:

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

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

To avoid such errors, you can use:

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

Alternative string syntax

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

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

Strings with quotes can be enclosed in single quotes:

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

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

Escape character \

By using a backslash, JavaScript will not interpret quotes as closing quotes.

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

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

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

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

Template literals

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

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

Template literals not only avoid errors when displaying quotes and apostrophes, but also provide support for inline expressions and multiline blocks, as discussed in the next section.

Multiline lines and newline

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

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

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

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

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

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

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

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

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

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

Conclusion

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

Tags:

When I write in javascript, I often have to turn to search engines in order to clarify the syntax of methods (and the order, definition of arguments) that work 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";

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");

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 to create a new string by "pulling" part of a substring from an existing string.

Using slice() :

Var stringOne = "abcdefghijklmnopqrstuvwxyz";

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

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

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 the regular expression has the "g" flag, 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.

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, a negative value will be returned if the original string is sorted before the string argument; if the string argument is sorted after the original string, +1 is returned. If null is returned, the two strings are equivalent.

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 again press.

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

An 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. … Creates a string from characters specified by Unicode codes. … Creates a string from characters specified by Unicode codes. … Creates a string from characters specified by Unicode codes. … Creates a string from characters specified by Unicode codes. … Creates a string from characters specified by Unicode codes. … Returns the position of the first occurrence of the specified substring. … Creates a string from characters specified by Unicode codes. … Creates a string from characters specified by Unicode codes. … Creates a string from characters specified by Unicode codes. ….

Returns the position of the last occurrence of the specified substring.

Compares two strings based on the operating system language. : 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. 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 lowercase. 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. Creates an HTML hyperlink ().") .

Wraps a string in tags

Compares two strings based on the operating system language. : Matches a string against a regular expression. length property Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object Syntax an object ). Wraps a string 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. blink method Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object .blink() blink ). Wraps a string in tags … returns a string consisting of a primitive string value

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

Compares two strings based on the operating system language. : Matches a string against a regular expression. bold method Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object .bold() blink ). Wraps a string in tags … bold . .

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

Compares two strings based on the operating system language. : Matches a string against a regular expression. My text charAt method) Converts an object to a string.: charAt method.charAt( Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object position any numeric expression charAt returns a string consisting of the character located in the given ). positions Matches a string against a regular expression. primitive string value

. Line character positions are numbered from zero to

Compares two strings based on the operating system language. : Matches a string against a regular expression.. -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. charAt method) Converts an object to a string.: charAt method.charAt( Converts all letters in a string to uppercase. charCodeAt method

Non-standard methods of the String object position.charCodeAt( charAt returns a string consisting of the character located in the given ).: numeric value Matches a string against a regular expression. returns a number equal to the Unicode code of the character located in the given . Line character positions are numbered from zero to. -1. If the position is outside this range, it returns

NaN

Compares two strings based on the operating system language. : Matches a string against a regular expression.. 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, …, .concat() Converts an object to a string.: 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, …, .concat( line0 Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object line1 stringN

Matches a string against a regular expression. + 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 + … + .concat(

any string expressions

concat

Compares two strings based on the operating system language. : Matches a string against a regular expression. returns a new string that is the concatenation of the original string and the method arguments. This method is equivalent to the operation Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object 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. blink ). Wraps a string 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. fontcolor method Converts an object to a string.: .fontcolor(color) color Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object string expression blink ). Wraps a string in tags .fontcolor(color)>… fontcolor

.

Compares two strings based on the operating system language. : Matches a string against a regular expression. 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) Converts an object to a string.: fontsize method.fontsize( Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object size blink ). Wraps a string in tags … numeric expression

fontsize

Compares two strings based on the operating system language. . 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, …, : String.fromCharCode() Converts an object to a string.: 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, …, : String.fromCharCode( code1 Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object code2 codeN 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, …, : String.fromCharCode(.

numeric expressions String fromCharCode

creates a new string (but not a string object) that is the concatenation of Unicode characters with codes

This is a static method of an object

Compares two strings based on the operating system language. : Matches a string against a regular expression., 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]?) Converts an object to a string.: Var s = String.fromCharCode(65, 66, 67); // s equals "ABC".indexOf( indexOf method.charAt( Converts all letters in a string to uppercase. charCodeAt method

Non-standard methods of the String object substring Start any string expression indexOf ).. Matches a string against a regular expression. indexOf method indexOf method indexOf method indexOf method returns first position Matches a string against a regular expression. Matches a string against a regular expression.

substrings

in a primitive string value

more than

Compares two strings based on the operating system language. : Matches a string against a regular expression. The search is carried out from left to right. Otherwise, this method is identical to the method. Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object The following example counts the number of occurrences of the substring pattern in the string str . blink ). Wraps a string in tags … 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

Compares two strings based on the operating system language. : Matches a string against a regular expression..italics() Var s = String.fromCharCode(65, 66, 67); // s equals "ABC"[,indexOf method]?) Converts an object to a string.: Var s = String.fromCharCode(65, 66, 67); // s equals "ABC".indexOf( indexOf method.charAt( Converts all letters in a string to uppercase. charCodeAt method

Non-standard methods of the String object italics. any string expression 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 ). Matches a string against a regular expression. lastIndexOf method indexOf method.lastIndexOf( indexOf method; indexOf method if not, then from position 0, i.e. from the first character of the line. If indexOf method returns first position Matches a string against a regular expression. negative, then it is taken equal to zero; If Matches a string against a regular expression.. -1, then it is taken equal

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

Compares two strings based on the operating system language. : Matches a string against a regular expression. Var n = "White whale".lastIndexOf("whale"); // n equals 6 link method) Converts an object to a string.: link method.link( Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object uri blink ). any string expression link link method, 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

Compares two strings based on the operating system language. : Matches a string against a regular expression.. For example, the statement document.write("My Text".link("#Bookmark")) is equivalent to the statement document.write("My Text") . concat method) Converts an object to a string.: concat method.link( Converts all letters in a string to uppercase. localeCompare method

.localeCompare(

Non-standard methods of the String object : number Support ). localeCompare compares two strings taking into account the national settings of the operating system. It returns -1 if primitive value less compares two strings taking into account the national settings of the operating system. It returns -1 if primitive value lines1

, +1 if it is greater

Compares two strings based on the operating system language. : Matches a string against a regular expression., and 0 if these values ​​are the same. match method) Converts an object to a string.: match method Converts all letters in a string to uppercase..match(

Non-standard methods of the String object regvyr match method ).: array of strings null match

  • . The result of the match is an array of found substrings or match method, if there are no matches. Wherein: match method.If(Matches a string against a regular expression. does not contain a global search option, then the method is executed match method exec
  • . The result of the match is an array of found substrings or match method) 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 match method.If(Matches a string against a regular expression., enclosed in parentheses. match method.contains a global search option, then the method) 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

lastIndex match method.If 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. match method It should be remembered that the method

changes object properties

Compares two strings based on the operating system language. : Matches a string against a regular expression.. Examples: match method,replace method) Matches a string against a regular expression.. Examples: match method,.replace() Converts an object to a string.: match method line .replace( function Converts all letters in a string to uppercase. regular expression string string expression

Non-standard methods of the String object function name or function declaration: new line match method replace ). matches regular expression match method with a primitive string value

. The result of the match is an array of found substrings or match method does not contain a global search option, then the search is performed for the first substring that matches match method and it is replaced. match method If match method contains a global search option, then all substrings matching

replace method, and they are replaced. , 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 . .replace( For example, the operator document.write("Tasty apples, juicy apples.".replace(/apples/g, "pears")) will display the line Delicious pears, juicy pears on the browser screen. match method If the second argument is function name or function declaration, 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

, 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

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")); match method.

will display the line 100C on the browser screen.

Please note that this method changes the properties of the object

Replace example

Replace all occurrences of a substring in a string

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

Compares two strings based on the operating system language. : Matches a string against a regular expression. Var str = "foobarfoobar"; str=str.replace(/foo/g,"xxx"); // the result will be str = "xxxbarxxxbar"; match method) Converts an object to a string.: match method search method Converts all letters in a string to uppercase..search(

Non-standard methods of the String object any regular expression: new line match method replace ).: numeric expression match method search match method. 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

is ignored, and properties

Compares two strings based on the operating system language. : Matches a string against a regular expression. do not change. indexOf method [,Examples:]?) Converts an object to a string.: indexOf method And Examples: slice method Converts all letters in a string to uppercase. regular expression string string expression

Non-standard methods of the String object .slice( ). end indexOf method any numerical expressions Examples: slice Examples: indexOf method, from position

to position Matches a string against a regular expression., without including it. If indexOf method Matches a string against a regular expression.. +indexOf method and until the end of the original line. Examples: Line character positions are numbered from zero to Matches a string against a regular expression.. +Examples:. -1. If the value

.

If the value

Compares two strings based on the operating system language. : Matches a string against a regular expression..small() Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object small blink ). Wraps a string 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. split method .split( [,delimiter]?) Converts an object to a string.: .split( number delimiter.fontsize( Converts all letters in a string to uppercase. string or regular expression : string array(object)

Non-standard methods of the String object Array split ). breaks the primitive value 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. delimiter Optional argument 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. Delimiter

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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. strike method Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object .strike() blink ). Wraps a string in tags … strike

.

Compares two strings based on the operating system language. : Matches a string against a regular expression. 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. Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object sub method blink ). Wraps a string in tags ….sub()

sub

Compares two strings based on the operating system language. : Matches a string against a regular expression.. charAt method [,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.]?) Converts an object to a string.: charAt method And 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. code1 Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object substr substr method )..substr( charAt length 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. returns a substring of the primitive value of a string 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. starting with this charAt and containing 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. characters. If

to position Matches a string against a regular expression. is not specified, then a substring is returned starting from the given one charAt method and until the end of the original line. If Matches a string against a regular expression. is negative or zero, an empty string is returned. charAt method is negative, then it is interpreted as an offset from the end of the line, i.e., it is replaced by Matches a string against a regular expression..+charAt method.

Note. If charAt method is negative, 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

Compares two strings based on the operating system language. : Matches a string against a regular expression..substring( indexOf method [,Examples:]) Converts an object to a string.: indexOf method And Examples: code1 Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object substring substr method ). end indexOf method any numerical expressions Examples: slice Examples: is not specified, then a substring is returned, starting from position indexOf method, from position

to position Matches a string against a regular expression.. -1. Negative arguments or equal . Line character positions are numbered from zero to are replaced by zero; if the argument is greater than the length of the original string, then it is replaced with it. If indexOf method more end, then they change places. If indexOf method 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

Compares two strings based on the operating system language. : Matches a string against a regular expression..sup() Converts all letters in a string to uppercase. Returns the primitive value of the object.

Non-standard methods of the String object sup blink ). Wraps a string 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. toLocaleLowerCase Method Converts all letters in a string to uppercase..toLocaleLowerCase()

.localeCompare(: new line

Non-standard methods of the String object : Internet Explorer Supported from version 5.5. Netscape Navigator Not supported. 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. toLocaleUpperCase Method Converts all letters in a string to uppercase..toLocaleLowerCase()

.localeCompare(: new line

Non-standard methods of the String object .toLocaleUpperCase() 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.

Compares two strings based on the operating system language. : Matches a string against a regular expression. toLowerCase method Converts all letters in a string to uppercase. regular expression string string expression

Non-standard methods of the String object .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 print the string object string to the browser screen.

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 of program code. Now let's get down to business!

String variable syntax

In the js language, all variables are declared using the var keyword, 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 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 variable values ​​into strings, but also perform arithmetic and logical operations with them, 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 Returns a substring given by position and 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 Returns a substring given by position 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! In this lesson we will look at how you can create a string and functions for working with strings in JavaScript. In principle, in JavaScript, any text variable is a string, since JavaScript is not a strongly typed programming language (read about data types). And also to work with strings the String class is used:

Var name1 = "Tommy";

So use the String constructor:

Var name1 = new String("Tommy");

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

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

String length

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

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

Search in a string

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

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

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

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

In the example, the message “Substring not found” will be displayed, since the string “Peter” is not contained in the string “Hello Vasya!”.

Functions includes, startsWith, endsWith

The more modern method str.includes(substr, pos) returns true if the string str contains the substring substr, or false if not.

This is the right choice if we need to check if there is a match, but the position is not needed:

Alert("Widget with id".includes("Widget")); // true alert("Hello".includes("Bye")); // false

The optional second argument to str.includes allows you to start the search at a specific position:

Alert("Midget".includes("id")); // true alert("Midget".includes("id", 3)); // false, search started from position 3

The str.startsWith and str.endsWith methods check, respectively, whether a string begins and ends with a specific string:

Alert("Widget". startsWith("Wid")); // true, "Wid" - the beginning of "Widget" alert("Widget".endsWith("get")); // true, "get" - ending "Widget"

Substring selection

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

The substring() function takes 2 arguments:

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

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

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

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

Var hello1 = "hello world. Goodbye world"; var bye1 = hello1.substr(12); document.write(bye1); //bye peace

Letter case control

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

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

Getting a symbol by its index

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

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

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

Removing spaces

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

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

Concatenating Strings

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

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

Substring replacement

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

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

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

Splitting a string into an array

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

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

String comparison

Also, when comparing strings, you should take into account the case of letters. The capital letter is smaller than the small letter, and the letter e is outside the alphabet in general.

TASKS

Changing the case of the last letter in a string

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

Spam check

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

Find the number

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

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



Have questions?

Report a typo

Text that will be sent to our editors: