javascript 在 Jquery 中访问值的最后三个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4393030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
access the last three Characters of the value in Jquery
提问by Someone
I have a value "319CDXB" everytime i have to access last three characters of the Strring how can i do this . Usually the Length varies all the time .Everytime I need the last characters of the String using Jquery
每次我必须访问 Strring 的最后三个字符时,我都有一个值“319CDXB”,我该怎么做。通常长度一直在变化。每次我需要使用 Jquery 的字符串的最后一个字符时
回答by user113716
The String .slice()methodlets you use a negative index:
该字符串.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.
编辑:稍微解释一下,.slice()String 的方法是一种行为非常类似于它的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.
只要范围有意义,任一参数都允许使用负索引。省略第二个参数意味着字符串的结束。
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. These two reasons make it (in my opinion) the most appealing option for obtaining a section of a String.
另一个好处.slice()是它在所有主要浏览器中都得到广泛支持。这两个原因使它(在我看来)成为获取字符串部分的最有吸引力的选择。
回答by James Kovacs
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 即可。
回答by H?vard
Simple:
简单的:
str = "319CDXB"
last_three = str.substr(-3)
回答by David Tang
var str = "319CDXB";
str.substr(str.length - 3); // "DXB"

