Js gets a summary of the last bit of the string

  • 2020-03-30 04:19:18
  • OfStack

Method 1: use the charAt method under the String object

The charAt() method returns a character at the specified location.


str.charAt(str.length � 1)

Note that JavaScript does not have a character data type that is different from a string type, so the character returned is a string of length 1

Method 2: use the substr method under the String object

The substr() method extracts a specified number of characters in a string starting with the start subscript.


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

Important: ECMAscript does not standardize this approach and therefore opposes its use.

Important: in IE 4, the value of the parameter start is invalid. In this BUG, start specifies the position of the 0th character. This BUG has been fixed in a later release.

Method 3: use the split method under the String object

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


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

Method 4: regex


<script type="text/javascript">
//<![CDATA[
var s = "nasofj;n234n41;v";
alert("String: "+s+"nn"+"LastOne: "+s.replace(/^(.*[n])*.*(.|n)$/g, "$2"));
//]]>
</script>

Above is what I know 4 kinds of methods, have recorded down, need a friend can refer to, if there are other methods also please inform, thank you


Related articles: