This article summarizes four methods for obtaining the last character of a string in JavaScript code. The example is provided, which is very simple and practical. We recommend it to you here.
Method 1: Use the charAt method of the String object
The charAt () method returns characters at a specified position.
The Code is as follows:
Str. charAt (str. length-1)
Please note that JavaScript does not have a character data type different from the string type, so the returned character is a string with a length of 1
Method 2: Use the substr method under the String object
The substr () method extracts a specified number of characters starting with the start subscript from a string.
The Code is as follows:
Str. substr (str. length-1, 1)
Important: ECMAscript does not standardize this method, so it is opposed to using it.
Important: in IE 4, the value of start is invalid. In this BUG, start specifies the position of 0th characters. (Www.jb51.net) in a later version, this BUG has been fixed.
Method 3: Use the split method under the String object
The split () method is used to split a string into a string array.
The Code is as follows:
Var str = 123456 ″;
Spstr = str. split ("");
Spstr [spstr. length-1];
Method 4: RegEx
The Code is as follows: