0
// 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.

2
  • 1
    mystring.length can't be unknown if you're accessing mystring. Commented Oct 3, 2015 at 20:46
  • var mystring = "This is an string"; alert(mystring.length); Commented Oct 3, 2015 at 20:54

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your solution.
0

I think you want slice:

"Mozilla".slice(0, -3); // "Mozi"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.