// Displays 'illa' the last 4 characters var mystring = 'Mozilla';
var mystring4 = mystring.substring(mystring.length - 4);
alert(mystring);
But how I will get string "Mozi" except last 3 character. when "mystring" length is unknown.
To get the first four characters, you could simply use:
var mystring = "Mozilla",
myStringFirstFourCharacters = mystring.substring(0,4);
console.log(myStringFirstFourCharacters); // "Mozi"
String.prototype.substring() takes two arguments; the start index and the end index; although the end-index is optional and, if missing, will be simply return the whole of the string after the start-index.
However, unlike String.prototype.substring(), if you know you want to take a substring of length 4 characters, you could simply use String.prototype.substr(), which takes a start index and a string-length argument:
var mystring = "Mozilla",
myStringFirstFourCharacters = mystring.substr(0,4);
console.log(myStringFirstFourCharacters); // "Mozi"
Although it's worth noting that if you're accessing a variable – mystring in this instance – then the length property will be known.
References:
mystring.lengthcan't be unknown if you're accessingmystring.var mystring = "This is an string"; alert(mystring.length);