tags:

views:

66

answers:

6

how to get the last element of string

e.g ="linto.yahoo.com.";

last element of this string is "."

How can find this?

+2  A: 
str.charAt(str.length - 1)

Some browsers allow (as a non-standard extension) you to shorten this to:

str[str.length - 1];
Matthew Flaschen
A: 

You can get the last char like this :

var lastChar=yourString.charAt(yourString.length-1);
Colin Hebert
+1  A: 

Use charAt:

The charAt() method returns the character at the specified index in a string.

You can use this method in conjunction with the length property of a string to get the last character in that string.
For example:

var myString = "linto.yahoo.com.";
var stringLength = myString.length; // this will be 16
var lastChar = myString.charAt(stringLength - 1); // this will be the string "."
Donut
+1 for first answer
steven_desu
A: 

Use the JavaScript charAt function to get a character at a given 0-indexed position. Use length to find out how long the String is. You want the last character so that's length - 1. Example:

var word = "linto.yahoo.com.";
var last = word.charAt(word.length - 1);
alert('The last character is:' + last);
Adam
A: 
mystring.substring(mystring.length - 1);
Kamikaze Mercenary
+1  A: 

An elegant and short alternative, is the String.prototype.slice method.

Just by:

str.slice(-1);

A negative start index slices the string from length+index, to length, being index -1, the last character is extracted:

"abc".slice(-1); // "c";
CMS
Side note: arrays also have a [`slice()`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice) method. - Their functionality is conceptually similar (partial copies) -------- (Just in case you're reading code and see `.slice()`)
Peter Ajtai