[英]how to get the first and the last character of a string using a Regex and Javascript
[英]How to get and return each last character of array to be in uppercase using javascript?
我有以下array
變量,我想使用javascript返回給定的數組,其中每個元素的最后一個字符都是Uppercase
的,我嘗試過如下所示,但不幸的是我得到了undefined
,請你幫我得到想要的輸出如下。 提前致謝。
期望的輸出: [onE, twO, threE, fouR]
var arr = ['one', 'two', 'three', 'four'];
var res = arr.map((item) => {
item.substr(arr.length) + item.charAt(arr.length -1).toUpperCase();
});
console.log(res);//[undefined, undefined, undefined, undefined]
您缺少退貨聲明:
var res = arr.map((item) => {
return item.slice(0,-1)+item.slice(-1).toUpperCase()
});
您還可以跳過大括號並返回關鍵字:
const arr = ['one', 'two', 'three', 'four'];
const res = arr.map(item =>
item.substring(0, item.length - 1) +
item.charAt(item.length - 1).toUpperCase()
)
console.log(res);
另請注意, String.prototype.substr被提及為已棄用(您可以使用 substring 代替)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.