Book of Coding


Strings

Strings are a primitive data type and are used very frequently in programming. These can be form entries of a user or data that you want to write to a file or to generate HTML dynamically, strings are required for all of this.

It is important to know how strings are structured and represented internally in JavaScript. In principle, strings are comparable to arrays. The first character is at position 0 (index 0), the second character at position 1 (index 1) and so on.


Internal structure of a string:
Rick Sample
0 1 2 3 4 5 6 7 8 9 10

1. Determine the length of a string

For example, a user should fill out a form with a user name, an e-mail address and a password in order to be able to register. However, it should be ensured that the user name is at least five characters long, but no longer than eight characters. To be able to decide this, the length of the string must be determined.

Complete Code - Examples/Part_189/main.js...

 function checkUsername(userName) {
   if(userName.length < 5) {
     console.error('User name must contain at least 5 characters.');
   } else if(userName.length > 8) {
     console.error('User name may contain a maximum of 8 characters.');
   } else {
     console.log('Valid user name');
   }
 }
 checkUsername('Rick');              // Error, too short
 checkUsername('RickSample');        // Error, too long
 checkUsername('RickS');             // valid
                        

Here, the checkUsername() function expects a character string (the user name) as an argument and uses the length property to determine the number of characters in the transferred character string. If less than five characters are contained, the error message User name must contain at least 5 characters. is displayed, if more than eight characters are contained, the error message User name may contain a maximum of 8 characters. is displayed. If the user name has the correct length, the message Valid user name is displayed.


2. Search within a string

Like arrays, strings offer the methods indexOf() and lastIndexOf(). However, strings are searched for individual characters or partial strings within strings. This is different from arrays, where these methods are used to search for elements in the array.


Search for the first instance

The first instance of a character or part of a string within another string is determined using the indexOf() method. The first argument is a character or string to be searched for. Optionally, a second argument can be passed, which is the position in the string from which the search is to start.

Complete Code - Examples/Part_190/main.js...

 const name = 'Summer Sample';
 console.log(name.indexOf('S'));         // output: 0
 console.log(name.indexOf('ample'));     // output: 8
                            

In the next example, a second argument is optionally specified for the index from which the search is to start. Here, the search is again for the S, but this time from index 2. The first two characters in the string are skipped during the search:

Complete Code - Examples/Part_191/main.js...

 const name = 'Summer Sample';
 console.log(name.indexOf('S', 2));      // output: 7
                            

Search for the last instance

The lastIndexOf() method searches from the end of a character string. Here too, the second parameter can be used to determine the index from which the search should start. However, this index counts from the end, but in the usual way.

Complete Code - Examples/Part_192/main.js...

 const name = 'Summer Sample';
 console.log(name.lastIndexOf('S'));         // output: 7
 console.log(name.lastIndexOf('S', 2));      // output: 0
                            

3. Extract parts of a string

Apart from the indexOf() and lastIndexOf() methods, arrays and character strings have another common method, namely the slice() method. For arrays, this method is used to copy parts of an array out of an array. The method behaves similarly for strings. The method copies parts out of a character string. The argument passed is the start index from which the copying is to begin and optionally the end index up to which the copying is to continue. If no end index is specified, the method copies from the start index to the end.

Complete Code - Examples/Part_193/main.js...

 const name = 'Summer Sample';
 console.log(name.slice(0, 6));      // output: "Summer "
 console.log(name.slice(7));         // output: "Sample"
 console.log(name.slice(7, 10));     // output: "Sam"
                            

This method also works with negative numbers:


 const name = 'Summer Sample';
 console.log(name.slice(-6, -3));    // Ausgabe: "Sam"
                            

There are other methods for extracting strings. The substring() method and the substr() method. Both methods expect the start index from which the substring is to be extracted as the first argument, a second argument can optionally be passed to both methods. In the case of substring(), the second argument denotes the index up to which extraction is to take place. In the case of substr(), it specifies the number of characters to be extracted from the start index. If the second argument is omitted, both methods behave in the same way, as extraction then simply takes place from the start index to the end of the string.

Complete Code - Examples/Part_194/main.js...

 const name = 'Summer Sample';
 console.log(name.substring(7, 10));     // Sam
 console.log(name.substring(7));         // Sample
 console.log(name.substr(7, 3));         // Sam
 console.log(name.substr(7));            // Sample
                            

Further methods for strings

The methods toLowerCase() and toUpperCase() can be used to convert all characters of a string into lowercase or uppercase letters. The repeat() method, which is passed a number as an argument, generates a new string based on a character string, in which the original character string occurs as often as specified. The charAt() method makes it possible to access individual characters of a character string at a specific index. With version ES2017, the methods padStart() and padEnd() were introduced. Both methods pad a given character string at the beginning or end with another string until a certain length is reached.


Related links: