Javascript 在javascript中,如何获取字符串中的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7447927/
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
in javascript, how can i get the last character in a string
提问by leora
If I have the following variable in javascript
如果我在 javascript 中有以下变量
var myString = "Test3";
what is the fastest way to parse out the "3" from this string that works in all browsers (back to IE6)
从适用于所有浏览器的字符串中解析出“3”的最快方法是什么(回到 IE6)
回答by Jamie Dixon
Since in Javascript a string is a char array, you can access the last character by the length of the string.
由于在 Javascript 中,字符串是一个字符数组,因此您可以通过字符串的长度访问最后一个字符。
var lastChar = myString[myString.length -1];
回答by Arnaud Le Blanc
It does it:
它做到了:
myString.substr(-1);
This returns a substring of myString starting at one character from the end: the last character.
这将返回 myString 的一个子字符串,从末尾的一个字符开始:最后一个字符。
This also works:
这也有效:
myString.charAt(myString.length-1);
And this too:
这也是:
myString.slice(-1);
回答by John Hartsock
var myString = "Test3";
alert(myString[myString.length-1])
here is a simple fiddle
这是一个简单的小提琴
回答by Joe
Javascript strings have a length
property that will tell you the length of the string.
Javascript 字符串有一个length
属性可以告诉你字符串的长度。
Then all you have to do is use the substr()
function to get the last character:
然后你所要做的就是使用该substr()
函数来获取最后一个字符:
var myString = "Test3";
var lastChar = myString.substr(myString.length -1);
edit: yes, or use the array notation as the other posts before me have done.
编辑:是的,或者使用数组符号作为我之前完成的其他帖子。
回答by diagonalbatman
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
你应该能够做类似上面的事情 - 这将得到最后一个字符
回答by Rob W
Use the charAt
method. This function accepts one argument: The index of the character.
使用charAt
方法。该函数接受一个参数:字符的索引。
var lastCHar = myString.charAt(myString.length-1);
回答by hmert
You should look at charAt function and take length of the string.
您应该查看 charAt 函数并获取字符串的长度。
var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));