Home > Web Front-end > JS Tutorial > Summary of js methods to get the last digit of a string_javascript skills

Summary of js methods to get the last digit of a string_javascript skills

WBOY
Release: 2016-05-16 16:31:22
Original
1523 people have browsed it

Method 1: Use the charAt method under the String object

The charAt() method returns the character at the specified position.

Copy code The code is as follows:

str.charAt(str.length – 1)

Please note that JavaScript does not have a character data type distinct from the string type, so the characters returned are strings of length 1

Method 2: Use the substr method under the String object

The

substr() method can extract the specified number of characters starting from the start subscript in the string.

Copy code The code is as follows:

str.substr(str.length-1,1)

Important: ECMAscript does not standardize this method and therefore discourages its use.

Important: In IE 4, the value of parameter start is invalid. In this BUG, ​​start specifies the position of the 0th character. (www.jb51.net) This BUG has been corrected in later versions.

Method 3: Use the split method under the String object

The split() method is used to split a string into an array of strings.

Copy code The code is as follows:

var str = “123456″;
spstr = str.split("");
spstr[spstr.length-1];

Method 4: Get it done with regular rules

Copy code The code is as follows:


The above are the 4 methods that I know. They are all recorded. Friends in need can refer to them. If you have other methods, please let me know. Thank you

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template