string = "LOL"; console.log(string.includes("lol")); // returns false console.log(string.includes("LOL")); // returns trueThe includes() method determines whether one string can be found in another string, returning true or false if necessary.
Syntax: -string.includes(searchString[, position])
searchString: - The string to search within this string.
position: -Additional. The position in this string at which to search searchString; default 0.
I have a shopping cart that displays product options in a dropdown menu, and if they select "yes" I want to make some other fields on the page visible.
The problem is that the shopping cart also includes a price modifier in the text, which can be different for each product. The following code works:
$(document).ready(function() ( $("select").change(function() ( var str = $("select option:selected").text(); if (str == "Yes (+ $6.95)") ( $(".engraving").show(); ) else ( $(".engraving").hide(); ) )); ));
However I would prefer to use something like this, which doesn't work:
$(document).ready(function() ( $("select").change(function() ( var str = $("select option:selected").text(); if (str *= "Yes") ( $(".engraving").show(); ) else ( $(".engraving").hide(); ) )); ));
I only want to perform an action if the selected option contains the word "Yes" and ignores the price modifier.
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. 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 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 an HTML hyperlink (). Wraps a string in tags . Wraps a string in tagslength property
Syntax : an 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 : an object.anchor( Name) Arguments: Name Result: string valueMethod 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 : an object.big() Result: string valueMethod 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 : an object.blink() Result: string valueMethod 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. The specified tags are not included in 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 : an object.bold() Result: string valueMethod 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 : an object.charAt( position) Arguments: position any numeric expression Result: string valueMethod 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 an 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 : an object.charCodeAt( position) Arguments: position any numeric expression Result: numeric valueMethod 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 an 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 : an object.concat( line0, line1, , stringN) Arguments: line0, line1, , stringN any string expressions Result: string valueMethod concat returns a new string that is the concatenation of the original string and the method arguments. This method is equivalent to the operation
an object + line0 + line1 + + stringNFor 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 : an object.fixed() Result: string valueMethod 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 : an object.fontcolor(color) Arguments: color string expression Result: string valueMethod 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 : an object.fontsize( size) Arguments: size numeric expression Result: string valueMethod 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 valueMethod 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 : an object.indexOf( substring[,Start]?) Arguments: substring any string expression Start any numeric expression Result: numeric valueMethod indexOf returns first position substrings in the primitive string value object. an object Start Start Start Start more than an object an 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 : an object.italics() Result: string valueMethod 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 : an object.lastIndexOf( substring[,Start]?) Arguments: substring any string expression Start any numeric expression Result: numeric valueMethod lastIndexOf returns last position substrings in the primitive string value object an 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 an object. -1, then it is taken equal an 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 : an object.link( uri) Arguments: uri any string expression Result: string valueMethod 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 : an object.localeCompare( line1) Arguments: line1 any string expression Result: numberSupport
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 : an object.match( Regvyr) Arguments: Regvyr Result: array of stringsMethod match Regvyr object. The result of the match is an array of found substrings or null, if there are no matches. Wherein:
- If Regvyr does not contain a global search option, then the method is executed Regvyr.exec(an 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(an 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 : an object.replace( Regvyr,line) an object.replace( Regvyr,function) Arguments: Regvyr regular expression string string expression function function name or function declaration Result: new lineMethod 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 : an object.search( Regvyr) Arguments: Regvyr any regular expression Result: numeric expressionMethod 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 : an object.slice( Start [,end]?) Arguments: Start And end any numerical expressions Result: new lineMethod 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 an object. -1. If the value Start an object. +Start. If the value end negative, then it is replaced by an 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 : an object.small() Result: string valueMethod 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 : an object.split( delimiter [,number]?) Arguments: delimiter 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.
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 separator. Operator
will display the line Text, bold, and italic on the browser screen.
strike method
Syntax : an object.strike() Result: string valueMethod 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 : an object.sub() Result: string valueMethod 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 : an object.substr( position [,length]?) Arguments: position And length numeric expressions Result: string valueMethod 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 an object. -1. If position greater than or equal to an 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 an 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 : an object.substring( Start [,end]) Arguments: Start And end numeric expressions Result: string valueMethod 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 an 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 : an object.sup() Result: string valueMethod 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 : an object.toLocaleLowerCase() Result: new lineSupport: 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 : an object.toLocaleUpperCase() Result: new lineSupport: 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 : an object.toLowerCase() Result: new lineMethod 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.
Last update: 06.04.2018
To create strings, we can either directly assign a string to a variable:
Let name = "Tom";
The String object is designed to work with strings, so you can also use the String constructor:
Var name = new String("Tom");
But as a rule, the first, shorter method is used. In the first case, JavaScript automatically converts the primitive type variable to a String object if necessary.
The String object has a large set of properties and methods with which we can manipulate strings.
The length property indicates the length of the string:
Var hello = "hello world"; console.log("In line "" + hello + "" " + hello.length + " characters");
The repeat() method allows you to create a string by repeating another string over and over again. The number of repetitions is passed as an argument:
Let hello = "hello"; console.log(hello.repeat(3)); // hello hello hello
Row patterns
String templates allow you to insert different values into a string. To do this, the lines are enclosed in forward quotes:
Let name = "Tom"; let hello = `Hello $(name)`; console.log(hello); // Hello Tom let age = 23; let info = `$(name) is $(age) years old`; console.log(info); //Tom is 23 years old
To insert a value into a string, it is braces, preceded by a dollar sign.
Also, instead of scalar values, properties of complex objects or results of expressions can be added:
Let tom =( name: "Tom", age: 25 ) let info = `$(tom.name) is $(tom.age) years old`; console.log(info); // Tom is 23 years old function sum(x, y)( return x + y; ) let a = 5, b = 4; let result = `$(a) + $(b) = $(sum(a, b))`; console.log(result); // 5 + 4 = 9
Search in a string
To search strings for a certain substring, the indexOf() (index of the first occurrence of the substring) and lastIndexOf() (index of the last occurrence of the substring) methods are used. These methods take two parameters:
Substring to find
An optional parameter that specifies from which character to search for a substring in a string
Both of these methods return the index of the character at which the substring begins in the string. If the substring is not found, then the number -1 is returned.
Let hello = "hello world. Bye peace"; let key = "world"; let firstPos = hello.indexOf(key); let lastPos = hello.lastIndexOf(key); console.log("First occurrence: ", firstPos); // 7 console.log("Last occurrence: ", lastPos); // 17
Another method - includes() returns true if the string contains a certain substring.
Let hello = "hello world. Bye peace"; console.log(hello.includes("world")); // true console.log(hello.includes("moment")); // false
With the help of the second additional parameter you can define the index from which the search for the substring will begin:
Let hello = "hello world. Bye peace"; console.log(hello.includes("world", 5)); // true console.log(hello.includes("hello", 6)); // false
Substring selection
To cut a substring from a string, use the substr() and substring() methods.
The substring() method takes two parameters:
index of the character in the string, starting from which the string should be trimmed
index to which the string should be truncated
The substr() method also takes the starting index of the substring as the first parameter, and the length of the substring to be cut as the second parameter:
Let hello = "hello world. Bye peace"; let bye = hello.substr(12, 4); console.log(bye); // Bye
If the second parameter is not specified, then the rest of the line is truncated:
Let hello = "hello world. Bye peace"; let bye = hello.substr(12); console.log(bye); // bye peace
Register management
To change the case, there are methods toLowerCase() (for converting to lower case) and toUpperCase() (for converting to upper case).
Let hello = "Hello Tom"; console.log(hello.toLowerCase()); // hello Tom console.log(hello.toUpperCase()); // HI TOM
Getting a symbol by index
To get a specific character in a string by index, you can use the charAt() and charCodeAt() methods. Both of these methods take the character index as a parameter:
Let hello = "Hello Tom"; console.log(hello.charAt(2)); // and console.log(hello.charCodeAt(2)); // 1080
But if the charAt() method returns the character itself as a result, then the charCodeAt() method returns the numeric code of this character.
Removing spaces
To remove leading and trailing spaces from a string, use the trim() method:
Let hello = "Hello Tom"; let beforeLength = hello.length; hello = hello.trim(); let afterLength = hello.length; console.log("Length of line up to: ", beforeLength); // 15 console.log("Line length after: ", afterLength); // 10
Concatenating Strings
The concat() method concatenates two strings:
Let hello = "Hello"; let world = "world"; hello = hello.concat(world); console.log(hello); // Hello World
Substring replacement
The replace() method replaces the first occurrence of one substring with another:
Let hello = "Good afternoon"; hello = hello.replace("day", "evening"); console.log(hello); // Good evening
The first parameter of the method specifies which substring should be replaced, and the second parameter specifies which substring should be replaced with.
String splitting
The split() method splits a string into an array of substrings using a specified delimiter. The separator is a string that is passed to the method:
Var message = "The weather was beautiful today"; var stringArray = message.split(" "); for(var str in stringArray) console.log(stringArray);
Browser output
The weather was beautiful today
Checking the beginning and end of a line
The startsWith() method returns true if the string starts with a specific substring. And the endsWith() method returns true if the string ends with a specific substring.
Let hello = "let me speak from my heart"; console.log(hello.startsWith("let")); // true console.log(hello.startsWith("Let")); // false console.log(hello.startsWith("lets")); // false console.log(hello.endsWith("heart")); // true console.log(hello.startsWith("bart")); // false
Case plays a role here, and from the example above we can see that "let" is not equivalent to "Let".
An additional second parameter allows you to specify the index (for startsWith - the index from the beginning, and for endsWith - the index from the end of the string) relative to which the comparison will be made:
Let hello = "let me speak from my heart"; console.log(hello.startsWith("me", 4)); // true, "me" - 4th index from the beginning of the line console.log(hello.startsWith("my", hello.length-8)); // true, "my" - 8th index from the end
When you write JavaScript, very often you have to surf the Internet in search of information about the syntax and parameters for methods that work with strings.
I've read a lot of articles on working with strings. This post will show examples and brief descriptions the most common methods for working with strings. I've tried to put the most common methods at the top for quick reference.
Of course, most experienced developers will already be fairly familiar with many of the techniques, but I think this is a good list for beginners to understand the range of techniques that can help accomplish complex operations with simple means.
Converting to String
You can convert a number, boolean expression, or object to a string:
Var myNumber = 24; // 24 var myString = myNumber.toString(); // "24"
You can do it the same way with String():
Var myNumber = 24; // 24 var myString = String(myNumber); // "24"
If you are not sure what the value is not null or undefined, you can use String(), which always returns a string, regardless of the value type.
Splitting a string into substrings
To split strings into an array of substrings you can use the method split():
Var myString = "coming,apart,at,the,commas"; var substringArray = myString.split(","); // ["coming", "apart", "at", "the", "commas"] var arrayLimited = myString.split(",", 3); // ["coming", "apart", "at"]
As seen in last line, the second parameter of the function is the limit on the number of elements that will be in the final array.
Getting the length of a string
To find how many characters there are in a string, we use the property length:
Var myString = "You"re quite a character."; var stringLength = myString.length; // 25
Finding a substring in a string
There are two methods to search for a substring:
Usage indexOf():
Var stringOne = "Johnny Waldo Harrison Waldo"; var wheresWaldo = stringOne.indexOf("Waldo"); // 7
indexOf() The method starts searching for a substring from the beginning of the string, and returns the position of the beginning of the first occurrence of the substring. In this case - 7th position.
Usage lastIndexOf():
Var stringOne = "Johnny Waldo Harrison Waldo"; var wheresWaldo = stringOne.lastIndexOf("Waldo"); // 22
The method returns the starting position of the last occurrence of a substring in a string.
Both methods return -1 if the substring is not found, and both take an optional second argument indicating the position in the string where you want the search to begin. So if the second argument is "5", indexOf() starts the search from character 5, ignoring characters 0-4, while lastIndexOf() starts the search at character 5 and works backwards, ignoring characters 6 and beyond.
Substring replacement
To replace an occurrence of a substring in a string with another substring, you can use replace():
Var slugger = "Josh Hamilton"; var betterSlugger = slugger.replace("h Hamilton", "e Bautista"); console.log(betterSlugger); // "Jose Bautista"
The first argument is what you want to replace and the second argument is the newline. The function replaces only the first occurrence of a substring in a string.
To replace all occurrences, you need to use a regular expression with a global flag:
Var myString = "She sells automotive shells on the automotive shore"; var newString = myString.replace(/automotive/g, "sea"); console.log(newString); // "She sells sea shells on the sea shore"
The second argument may include a special template or function. You can read more.
Get a character at a given position in a string
We can get the symbol using the function charAt():
Var myString = "Birds of a Feather"; var whatsAtSeven = myString.charAt(7); // "f"
As is often the case in JavaScript, the first position in the string starts at 0, not 1.
As an alternative function you can use charCodeAt() function, which is the character code.
Var myString = "Birds of a Feather"; var whatsAtSeven = myString.charCodeAt(7); // "102" var whatsAtEleven = myString.charCodeAt(11); // "70"
Note that the code for the "F" character (position 11) is different than the "f" character (position 7).
Concatenating Strings
In most cases, you can use the "+" operator to concatenate strings. But you can also use the method concat():
Var stringOne = "Knibb High football"; var stringTwo = stringOne.concat("rules."); // "Knibb High football rules"
In this way we can combine many lines into one in the order in which they are written:
Var stringOne = "Knibb"; var stringTwo = "High"; var stringThree = "football"; var stringFour = "rules."; var finalString = stringOne.concat(stringTwo, stringThree, stringFour); console.log(finalString); // "Knibb high football rules."
Substring extraction
There are 3 ways to get a string from part of another string:
Using slice():
Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.slice(5, 10); // "fghij"
Using substring():
Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.substring(5, 10); // "fghij"
In both functions, the first parameter is the character at which the substring begins (starting from position 0) and the second argument (optional) is the position of the character up to which the substring is returned. The example (5, 10) returns the string between positions 5 and 9.
Using substr():
Var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne.substr(5, 10); // "fghijklmno"
The first argument is the position of the character at which the new line begins and the second argument is the number of characters from the starting position of the new line. Those. (5, 10) returns 10 characters, starting at position 5.
Convert a string to upper or lower case.
There are 4 methods for translation. The first 2 convert the string to uppercase:
Var stringOne = "Speak up, I can"t hear you."; var stringTwo = stringOne.toLocaleUpperCase(); // "SPEAK UP, I CAN"T HEAR YOU" var stringThree = stringOne.toUpperCase(); // "SPEAK UP, I CAN"T HEAR YOU"
The other 2 convert the string to lower case:
Var stringOne = "YOU DON"T HAVE TO YELL"; var stringTwo = stringOne.toLocaleLowerCase(); // "you don"t have to yell" var stringThree = stringOne.toLowerCase(); // "you don"t have to yell"
It's better to use "locale" methods, because... in different places, for example, in Turkey, the display of registers does not work quite the way we are used to and therefore the result may be the one we wanted. If you use “locale” methods, then there will be no such problems.
Pattern Matching
Pattern matching on a string can be done using 2 methods, which work differently.
Method match() is applied to a string and it takes a regular expression as a parameter:
Var myString = "How much wood could a wood chuck chuck"; var myPattern = /.ood/; var myResult = myString.match(myPattern); // ["wood"] var patternLocation = myResult.index; // 9 var originalString = myResult.input // "How much wood could a wood chuck chuck"
Method exec() applied to a regular expression object and takes the string as a parameter:
Var myString = "How much wood could a wood chuck chuck"; var myPattern = /.huck/; var myResult = myPattern.exec(myString); // ["chuck"] var patternLocation = myResult.index; // 27 var originalString = myResult.input // "How much wood could a wood chuck chuck"
In both methods, only the first match is returned. If there are no matches, it returns null.
You can also use the method search() which takes a regular expression and returns the position of the first match in the pattern:
Var myString = "Assume"; var patternLocation = myString.search(/ume/); // 3
If there were no matches, “ -1 «.
Comparing two strings for sorting
You can compare 2 strings to determine which comes first in the alphabet. To do this, we will use the method localeCompare() which returns 3 possible values:
Var myString = "chicken"; var myStringTwo = "egg"; var whichCameFirst = myString.localeCompare(myStringTwo); // -1 (Chrome returns -2) whichCameFirst = myString.localeCompare("chicken"); // 0 whichCameFirst = myString.localeCompare("apple"); // 1 (Chrome returns 2)
As shown above, a negative number is returned if the string argument comes after the original string. Positive number, if the string argument comes before the original string. If returned 0 - means the lines are equal.
To check the return value it is better to use if (result< 0), чем if (result === -1). Последнее не будет работать в Chrome.
Thank you for your attention, I hope that you learned a lot of new and interesting things!
Author of the article: Alex. Category:Date of publication: 03/19/2013