4 methods: 1. Use "str.charAt(str.length-1)" to intercept the last 1 digit of the string; 2. Use "str.substr(str.length-N)", The last N digits can be intercepted; 3. Use "str.slice(str.length-N)" to intercept the last N digits, etc.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 method of intercepting the last digits of a string
Method 1: Use charAt() to intercept the last digit
The charAt method is to return a character at the specified position
var str="123456"; console.log(str); var c=str.charAt(str.length-1); console.log("后一位:"+c);
##Method 2: Use substr() to intercept the last N digits
The substr method can extract characters of a specified length from the beginning of the character. Syntax:str.substr(str.length - N)
var str="123456"; console.log(str); console.log("后1位:"+str.substr(str.length-1)); console.log("后2位:"+str.substr(str.length-2)); console.log("后3位:"+str.substr(str.length-3)); console.log("后4位:"+str.substr(str.length-4));
Method 3: Use slice() to intercept the last N bits
The two parameters of slice represent the starting position and The end position includes the starting position and does not include the end position. If omitted, it means the end position. Syntax:str.slice(str.length - N)
var str="123456"; console.log(str); console.log("后1位:"+str.slice(str.length-1)); console.log("后2位:"+str.slice(str.length-2)); console.log("后3位:"+str.slice(str.length-3)); console.log("后4位:"+str.slice(str.length-4)); console.log("后5位:"+str.slice(str.length-5));
Method 4: Use substring to intercept the last N digits
str.substring(start, end)The method also intercepts a string. The two parameters represent the starting and ending digits respectively, similar to slice, but the difference is that substring does not accept negative numbers, and if the start value is greater than the end value, the two positions will be automatically swapped
str.substring(str.length-N))
var str="123456"; console.log(str); console.log("后1位:"+str.substring(str.length-1)); console.log("后2位:"+str.substring(str.length-2)); console.log("后3位:"+str.substring(str.length-3));
javascript video tutorial,web front-end]
The above is the detailed content of How to intercept the last few digits of a string in es6. For more information, please follow other related articles on the PHP Chinese website!