簡體   English   中英

如何獲取字符串的最后一個字符?

[英]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";

使用charAt

charAt() 方法返回字符串中指定索引處的字符。

您可以將此方法與字符串的length屬性結合使用以獲取該字符串中的最后一個字符。
例如:

 const myString = "linto.yahoo.com."; const stringLength = myString.length; // this will be 16 console.log('lastChar: ', myString.charAt(stringLength - 1)); // this will be the string

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));

使用 JavaScript charAt函數在給定的 0 索引位置獲取字符。 使用length找出字符串的長度。 您需要最后一個字符,因此長度為 - 1。示例:

var word = "linto.yahoo.com.";
var last = word.charAt(word.length - 1);
alert('The last character is:' + last);
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM