substring follows the syntax:
Where start indicates from which character it must begin, while end indicates the end of the character to be considered.
The start parameter is mandatory and if it is not specified, the value 0 is considered. Instead, the end parameter is optional and if not specified, it considers the string up to the last character.
Let’s see immediately a first example of using this method to understand its correct functioning.
Transform a lowercase name into an uppercase name using the substring method and also the toUpperCase method.
First of all you need to insert a lowercase name in a variable, for example I entered coding.
Now you need to change the first letter to uppercase.
The first letter is extracted by simply pointing to the first string element .
Then we need to concatenate the two strings and we can do it simply with the + operator.
var word= 'coding'; var firstLetter = string.toUpperCase(); var letters = string.substring(1); var wordCapital = firstLetter + letters; document.write('The modified string is: ' + wordCapital);
In this second example we extract the first letter of the name, the first letter of the surname entered in input and transform them, so as to always have the first letter in uppercase and all the rest in lowercase.
When the user has entered the data and clicked ok, he will call the transform function which will transform the data as indicated.
To make this example we need the methods toUpperCase, toLowerCase and substring.
var name = prompt('Insert the name: '); name = name.toUpperCase() + name.substring(1).toLowerCase(); var lastname= prompt('Insert lastname: '); lastname = lastname.toUpperCase() + lastname.substring(1).toLowerCase(); document.getElementById("result").innerHTML = "Name and lLastname: " + name + ' ' + lastname;
Clearly we will assume that the user enters a word longer than 2 letters. If the user enters a string of only 1 character, the latter will still be returned.
Here is the complete code:
var name = prompt('Insert the name: '); var len = name.length; var lastTwo = name.substring(len-2); document.getElementById("result").innerHTML = lastTwo ;
Clearly, a check could be made to allow the insertion of at least two characters of text.