简体   繁体   English

访问Jquery中值的最后三个字符

[英]access the last three Characters of the value in Jquery

I have a value "319CDXB" everytime i have to access last three characters of the Strring how can i do this . 我有一个值“319CDXB”每次我必须访问Strring的最后三个字符我该怎么做。 Usually the Length varies all the time .Everytime I need the last characters of the String using Jquery 通常长度会一直变化。每次我都需要使用Jquery的字符串的最后一个字符

The String .slice() method lets you use a negative index: String .slice()方法允许您使用负索引:

var str = "319CDXB".slice( -3 ); // DXB

EDIT: To expound a bit, the .slice() method for String is a method that behaves very much like its Array counterpart . 编辑:为了解释一下,String的.slice()方法是一种行为非常类似于Array对应的方法

The first parameter represents the starting index, while the second is the index representing the stopping point. 第一个参数表示起始索引,而第二个参数表示停止点。

Either parameter allows a negative index to be employed, as long as the range makes sense. 只要范围有意义,任一参数都允许使用负指数。 Omitting the second parameter implies the end of the String. 省略第二个参数意味着String的结束。

Example: http://jsfiddle.net/patrick_dw/N4Z93/ 示例: http //jsfiddle.net/patrick_dw/N4Z93/

var str = "abcdefg";

str.slice(0);        // "abcdefg"
str.slice(2);        // "cdefg"
str.slice(2,-2);     // "cde"
str.slice(-2);       // "fg"
str.slice(-5,-2);    // "cde"

The other nice thing about .slice() is that it is widely supported in all major browsers. 关于.slice()的另一个.slice()是它在所有主流浏览器中得到广泛支持。 These two reasons make it (in my opinion) the most appealing option for obtaining a section of a String. 这两个原因(在我看来)是获取String的一部分最吸引人的选择。

You can do this with regular JavaScript: 您可以使用常规JavaScript执行此操作:

var str = "319CDXB";
var lastThree = str.substr(str.length - 3);

If you're getting it from jQuery via .val(), just use that as your str in the above code. 如果你是通过.val()从jQuery获取它,只需在上面的代码中使用它作为你的str。

Simple: 简单:

str = "319CDXB"
last_three = str.substr(-3)
var str = "319CDXB";
str.substr(str.length - 3); // "DXB"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM