如何获取字符串的最后一个字符:

"linto.yahoo.com."

这个字符串的最后一个字符是“。”

我怎么才能找到这个?


当前回答

一个简单的方法是使用这个:)

var word = "waffle"
word.endsWith("e")

其他回答

使用charAt:

charAt()方法的作用是:返回字符串中指定下标处的字符。

您可以将此方法与字符串的length属性结合使用,以获取该字符串中的最后一个字符。 例如:

const myString = "linto.yahoo.com."; const stringLength = myString.length;//这将是16 console.log('lastChar: ', myString. log)charAt(stringLength - 1));//这将是字符串

你可以像这样得到最后一个char:

var lastChar=yourString.charAt(yourString.length-1);

一个优雅而简短的替代方法是String.prototype.slice方法。

仅仅通过:

str.slice(-1);

负起始索引将字符串从长度+索引切片到长度,即索引-1,最后一个字符被提取:

"abc".slice(-1); // "c";

使用String.prototype.at()方法是实现它的一种新方法

Const s = "linto.yahoo.com."; Const last = s.at(-1); console.log(去年);

阅读更多关于at的资料

你可以使用下面的方法。在这种情况下,最后一个字符是多余的,但对于子字符串,它是有用的:

var word = "linto.yahoo.com.";
var last = ".com.";
if (word.substr(-(last.length)) == last)
alert("its a match");