[英]How can I cut the last char from a string in jquery?
suppose that i have 假设我有
var name = "kanishka"; var name =“kanishka”;
How can I cut only the last char so that the output will be 'a' instead? 如何只剪切最后一个字符,以便输出为'a'?
i read the question 我读了这个问题
How can I cut the 1st char from a string in jquery? 如何从jquery中的字符串中剪切第一个字符?
by jin Yong , 由金勇,
in this problem i know the length of the string . 在这个问题我知道字符串的长度。 can u tell me how i can do this with out knowing the string length . 你可以告诉我如何知道字符串长度我能做到这一点。
couldn't get help from the answers , please help 无法从答案中获得帮助,请帮忙
Using plain javascript, you can do 使用普通的javascript,你可以做到
name.charAt(name.length-1)
More information on charAt http://www.w3schools.com/jsref/jsref_charat.asp 有关char的更多信息, 请访问http://www.w3schools.com/jsref/jsref_charat.asp
Array.prototype.pop.apply(name);
^_^ ^ _ ^
or if you want to be boring: 或者如果你想要无聊:
name.substr(name.length-1);
or: 要么:
name.split('').reverse().shift()
or: 要么:
name.split(name.substr(0, name.length-1)).pop()
or: 要么:
name.constructor.prototype.charAt.call(name.split('').reverse(), 0)
or: 要么:
var chr; name.split('').forEach(function(c){ chr=c; });
or (okay, these are serious): 或者(好吧,这些都很严重):
/.$/.exec(name)[0]
or 要么
name[name.length-1];
If you want the "a" in "kanishka": 如果你想要“kanishka”中的“a”:
var name = "kanishka";
name = name.substring(name.length - 1);
name = name.substr(name.length-1,name.length);
A roundup of your options as presented by the various answers here: 这里有各种答案所示的综合选项 :
(note that this is a CW answer, as it represents community content) (请注意,这是一个CW答案,因为它代表了社区内容)
substring
: substring
:
var lastChar = name.substring(name.length - 1);
substr
: substr
:
var lastChar = name.substr(name.length - 1);
slice
: slice
:
var lastChar = name.slice(-1);
charAt
: charAt
:
var lastChar = name.charAt(name.length - 1);
[]
) on most browsers (usually by a fair margin). 在大多数浏览器上最快(或与[]
最快结合)(通常是公平的)。 []
: []
:
var lastChar = name[name.length - 1];
charAt
) on most browsers (usually by a fair margin). 在大多数浏览器上最快(或与charAt
最快结合)(通常是公平的)。 (Due respect to cwolves' flights of outre approaches, I stuck to the mainstream like the boring plodder I am.) (考虑到cwolves的飞行方式,我坚持主流,就像我无聊的笨蛋一样。)
Gratuitous jsperf test 无偿的jsperf测试
Which should you use? 你应该用哪个? It's totally up to you. 这完全取决于你。 Note that all of the options above are plenty fast, the odds that the speed of this operation are actually important in 99.999% of real-world cases are very low indeed. 请注意,上面的所有选项都非常快,在99.999%的实际情况下,此操作的速度实际上非常重要的可能性非常低。
一种简洁,简洁,跨浏览器的方式
name.slice(-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.