Javascript - string - remove substring from js string. Javascript methods for working with strings Getting a character by index

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

string = "LOL"; console.log(string.includes("lol")); // returns false console.log(string.includes("LOL")); // returns true

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.

Last update: 04/06/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 enclosed in curly 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

Using the second additional parameter, you can determine 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

let hello = "hello world. Bye peace"; let world = hello.substring(7, 10); // from 7th to 10th index console.log(world); // world

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 toLowerCase() methods (for converting to lower case) and toUpperCase() (for translation to uppercase).

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 I write in javascript, I often need to refer to search engines, in order to clarify the syntax of methods (and order, definition of arguments) working with strings.

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

Convert to string

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

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

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

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

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

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

Split a string into substrings

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

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

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

Get string length

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

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

Define a substring in a string

There are two ways to achieve your plan:

Use indexOf() :

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

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

Use lastIndexOf() :

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

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

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

How to replace part of a string

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

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

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

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

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

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

Find a character at a given position

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

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

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

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

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

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

String concatenation in javascript

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

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

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

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

Part of a string (extract substring in javascript)

There are three different ways 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"

Using substring() :

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

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

Using substr() :

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

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

Converting a string to lower or upper case in javascript

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

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

And two to convert the string to 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.

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

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

Comparing two strings for later sorting

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

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

As shown above, 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 returned null value, the two strings are equivalent.

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 quite familiar with many of the techniques, but I think this good list for beginners to understand the range of techniques that can help perform 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 you can see in the 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. A 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
Computer