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

"linto.yahoo.com."

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

我怎么才能找到这个?


当前回答

如果你已经或正在使用lodash,请使用last:

_.last(str);

它不仅比普通JS更简洁和明显,它也更安全,因为它避免了Uncaught TypeError:当输入为null或未定义时不能读取属性X为undefined,所以你不需要事先检查:

// Will throw Uncaught TypeError if str is null or undefined
str.slice(-1); 
str.charAt(str.length -1);

// Returns undefined when str is null or undefined
_.last(str);

其他回答

使用JavaScript的charAt函数获取给定0索引位置的字符。使用length来找出字符串的长度。最后一个字符的长度是- 1。 例子:

var word = "linto.yahoo.com.";
var last = word.charAt(word.length - 1);
alert('The last character is:' + last);

使用charAt:

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

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

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

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

仅仅通过:

str.slice(-1);

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

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

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

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

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

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