As we've already learned, the String object stores and processes text values. This data type is often used, and to process these values there are multiple methods in JavaScript. Note that when any of these methods is applied, a new string is created to the same variable. Let's review all the important methods of processing strings.
Substring search
The indexOf()
method returns the index of the first occurrence of the specified value found.
Syntax:
string.indexOf(substring, index)
where:
string - a string to search a substring in
substring - a string searched
index - position to start the search from (optional)
The search is performed from the beginning to the end of the line. By the way, if there are several occurrences of the substring, the index of the first occurrence will be returned. If there are no matches, it returns -1. The first index is 0, the second is 1, and so on. For example:
var str = "London is the capital of Great Britain";
var a = str.indexOf('i', 10); // 17
var b = str.indexOf('on'); // 1
var c = str.indexOf('on',3); // 4
var d = str.indexOf('USA'); // -1
var e = str.indexOf('capital') // 14
There is a very similar method called lastIndexOf()
. Syntax and the return value are the same as in indexOf()
. The only difference is that the lastIndexOf()
method returns the index of the last occurrence of the substring.
var a = str.lastIndexOf('on'); // 4
var b = str.indexOf('ta'); // 18
var c = str.lastIndexOf('ta'); // 34
There is yet another way to find a substring - search()
. The syntax of this method is the same as in previously mentioned indexOf()
and lastIndexOf()
, however functionality differs.
The search()
method does not accept the second parameter, so it always starts the search with the first character. Also, the indexOf()
method cannot work with regular expressions like the search()
.
There is a Boolean method - includes()
. It returns "true" if a string contains a specific substring.
var str = "London is the capital of Great Britain";
var a = str.includes('capital'); // true
var b = str.includes('capitan'); // false
Іn this method, you can also specify the second parameter from which to start the search:
var c = str.includes('capital', 24) // false
There are two other Boolean search methods such as endsWith()
and startsWith()
. The first one will return "true" if the string starts with the characters specified as the first parameter, and "false" if not. The second one will return "true" if the string ends with the characters specified as the first parameter, and "false" if not.
These two methods can take the second numerical parameter. For endsWith()
this parameter will specify the search range, while for startsWith()
the parameter will specify from which character you want to start the search.
var str = "Hello my dear friends!";
alert(str.startsWith("Hello")); // true
alert(str.startsWith("my")); // false
alert(str.startsWith("my",6)); // true
alert(str.endsWith("ello",5)); // true
alert(str.endsWith("ello",)); // false
Find substring
There is also a group of methods that can cut out a part of the string from the input string. Let's start with slice()
. It takes two indexes as parameters. The first index indicates which character to cut the word from, the second is the index indicating where to stop.
var str = "Hello, my dear friends!";
alert(str.slice(7,14)); // my dear
alert(str.slice(1,-9)); // ello, my dear
alert(str.slice(-14, -1)); // dear friends
alert(str.slice(-16)); // my dear friends!
Based on these examples, we see that when the index is negative, the position is counted from the end of the input string, the count here also starts from zero. And if you skip the second parameter, the program will consider it equal to the length of the string.
By the way, there is a similar method - substring()
. The difference is that the substring()
method does not accept negative parameters. In slice()
the first parameter should be lesser than the second. In substring()
, if the first parameter is greater than the second one, they change places. Let's look at this example.
alert(str.substring(10)); // dear friends!
alert(str.substring(7, 14)); // my dear
alert(str.substring(14, 7)); // my dear
alert(str.slice(14, 7)); // -
The third in this group of methods is the substr()
method. It differs in that its second parameter indicates the length of the string to be pulled out.
alert(str.substr(0, 5)); // Hello
alert(str.substr(7)); // my dear friends!
alert(str.substr(-13)); // dear friends!
alert(str.substr(-13, 4)); // dear
In substr()
the first parameter can be a negative number, so the program will subtract the value from the end of the string. But the second parameter cannot be negative, because it indicates the length of the string we want to cut.
As in the previous two methods, if you do not specify the second parameter in substr()
, the program will select the whole string, starting with the specified index.
There are similar methods for obtaining single characters, although used rarely:
charAt(index)
It returns a string character located at a specified position.
charCodeAt(index)
It returns the code of the string character located at a specified position.
Replace substring
When you'd like to change something in a string, there is the replace()
method for example. This method utilizes two parameters - what to replace and what value to replace with. The method will first try to find the specified value in the input line, and if it finds it, it will replace it with the required one.
var x = "Hello world!";
alert(x); // Hello world!
var y = x.replace("world", "friends");
alert(y); // Hello friends!
It is important to say that this method is case sensitive, i.e. if you specify "WORLD" instead of "world", the program will not find this word in the string. We will mention how to convert the whole string to lowercase or uppercase in a moment. There is one more option to replace the value despite the case: a regular expression ‘/i
':
var x = "Hello world, hello my dear world!";
alert(x);
var y = x.replace(/WORLD/i, "friends");
alert(y);
Іf there are several occurrences of the word in this line, the method will replace the first one only:
var x = "Hello world, hello my dear world!";
alert(x); // Hello world, hello my dear world!
var y = x.replace("world", "friends");
alert(y);
Upper / lower case
There are 2 special methods designed to convert each character of the input string to uppercase (toUpperCase()
) or lowercase (toLowerCase()
). Both methods do not accept any parameters.
var x = "Hello world, hello my dear world!";
alert(x); // Hello world, hello my dear world!
var y = x.replace(/world/g, "friends");
alert(y); // Hello friends, hello my dear friends!
Length
The length
method returns the length of the input string:
var name = "Anna";
var name_length = txt.length; //return 4
It is often used, for example, for registration forms:
var name = prompt("Please, input your name");
if(name.length < 2)
{
var x = alert("Name is too short");
}
Gaps
A group of methods that allow you to remove extra spaces in the string, or add gaps as well. Let's start with the ladder. PadStarts()
and padEnd()
methods take two parameters: the second - the character you want to add, the first - the string length we want to achieve.
var str = "Look";
var x = str.padStart(10, ' ');
alert(x); // Look
alert(x.length); //10
var y = str.padEnd(8, '!');
alert(y); //Look!!!!
alert(y.length); //8
Now let's learn to remove extra spaces with the Trim()
, trimStart()
, trimEnd()
methods. All of them do not accept any parameters.
var str = " Look ";
var x = str.trim();
alert(x); //Look
alert(x.length); //4
var y = str.trimStart();
alert(y); //Look.....
alert(y.length); //9
var z = str.trimEnd();
alert(z); // Look
alert(z.length); //9
Repeat string
The repeat()
method creates a string by repeating a string multiple times. The number of repetitions is indicated in parentheses.
var x = "Hi! ";
alert(x.repeat(4)); // Hi! Hi! Hi! Hi!
Connecting strings
Concat() is a very well known method that allows you to combine several strings into one.
var str1 = "Very";
var str2 = "well";
alert(str1.concat(' ', str2, '!')); // Very well!
Convert string to array
There is often a need to convert one input string to an array of values. For example, if you are reading data from a text file where it is written in a row, and you need to split it.
The method is called to the input string, and the delimiter must be specified as a parameter. Most often the separator is a space or a comma, but you can specify any character there.
var str = "John Smith male 26 footballer";
var array = str.split(' ');
var name = array[0];
var surname = array[1];
var sex = array[2];
var age = array[3];
var profession = array[4];
alert(name + ' ' + surname + " (" + sex + ") is " + age + " years old, " + profession);
// John Smith (male) is 26 years old, footballer
Аnd if you do not specify a parameter, the method itself creates an array of characters.
var str = "Hello";
var array = str.split("");
var text = "";
for (var i = 0; i < array.length; i++)
{
text += array[i] + ", "
}
alert(text); //H, e, l, l, o,
Unicode
You've heard about Unicode, the global text standard. JavaScript also has string methods for it specifically. In particular, there is a method that returns a numeric value by index from the Unicode table:
alert("A".charCodeAt()); //65
alert("*".charCodeAt()); //42
And vice versa: returns value from index in Unicode table to number or character:
alert(String.fromCharCode(42)); //*
alert(String.fromCharCode(112)); //p