[英]How to get the last character of a string?
如何獲取字符串的最后一個字符:
"linto.yahoo.com."
該字符串的最后一個字符是"."
我怎樣才能找到這個?
一個優雅而簡短的替代方法是String.prototype.slice
方法。
只是通過:
str.slice(-1);
負起始索引將字符串從length+index
index 切片到length
,即索引-1
,提取最后一個字符:
"abc".slice(-1); // "c";
str.charAt(str.length - 1)
某些瀏覽器允許(作為非標准擴展)您將其縮短為:
str[str.length - 1];
您可以使用不同的方式但具有不同的性能來實現這一點,
1. 使用括號表示法:
var str = "Test"; var lastLetter = str[str.length - 1];
但不建議使用括號。 檢查這里的原因
2.charAt[索引]:
var lastLetter = str.charAt(str.length - 1)
這是可讀和最快的。 這是最推薦的方式。
3.子串:
str.substring(str.length - 1);
4.切片:
str.slice(-1);
它比子字符串略快。
您可以在此處查看性能
使用 ES6:
您可以使用str.endsWith("t");
但它在 IE 中不受支持。 在此處查看有關endsWith的更多詳細信息
將substr與參數-1一起使用:
"linto.yahoo.com.".substr(-1);
等於“.”
注意:
要從字符串的末尾提取字符,請使用負的起始編號(這在 IE 8 及更早版本中不起作用)。
使用String.prototype.at()
方法是一種新的實現方式
const s = "linto.yahoo.com."; const last = s.at(-1); console.log(last);
at
此處閱讀更多信息
一個簡單的方法是使用這個:)
var word = "waffle"
word.endsWith("e")
您可以像這樣獲得最后一個字符:
var lastChar=yourString.charAt(yourString.length-1);
試試這個...
const str = "linto.yahoo.com."
console.log(str.charAt(str.length-1));
var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];
您可以使用以下內容。 在最后一個字符的情況下,這是一種矯枉過正,但對於子字符串,它很有用:
var word = "linto.yahoo.com.";
var last = ".com.";
if (word.substr(-(last.length)) == last)
alert("its a match");
如果您已經或正在使用 lodash,請改用last :
_.last(str);
它不僅比 vanilla JS 更簡潔明了,而且更安全,因為它避免了Uncaught TypeError: Cannot read property X of undefined
when the input is null
or undefined
所以你不需要事先檢查這個:
// Will throws 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);
如何獲取字符串的最后一個字符:
"linto.yahoo.com."
該字符串的最后一個字符是"."
我怎么能找到這個?
你可以使用這個簡單的 ES6 方法
const lastChar = (str) => str.split('').reverse().join(',').replace(',', '')[str.length === str.length + 1 ? 1 : 0]; // example console.log(lastChar("linto.yahoo.com."));
這將適用於所有瀏覽器。
var string = "Hello"; var fg = string.length; fg = fg - 1; alert(string[fg]);
您還可以將字符串轉換為數組並獲取最后一項,
var str = "Hello world!";
var arr = str.split('');
var lastItem = arr[arr.length - 1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.