Я пытаюсь сделать первую букву массива заглавной со строками, я добавляю свой метод в String
, но он возвращает только первую букву с заглавной буквы, а не полное предложение. Так что это должно быть "Привет, как дела?"
const str = "Hi there how are you?";
String.prototype.toJadenCase = function(st) {
let arr = st.split(" ");
arr.forEach(function(ele, index) {
arr[index] = ele.charAt(0).toUpperCase();
});
return arr;
};
console.info(String.prototype.toJadenCase("Hi there how are you"));
Возвращает массив только первой буквы, а не полного слова ["H", "T", "H", "A", "Y"]
посмотрите на stackoverflow.com/questions/1026069/…
Это также можно сделать с помощью string.replace()
. Что-то вроде этого: const toJadenCase = (str) => str.replace(/\s./g, m => m.toUpperCase())
Вам также нужно добавить оставшуюся часть строки
const str = "Hi there how are you?";
String.prototype.toJadenCase = function (st) {
let arr = st.split(" ");
arr.forEach(function(ele, index) {
arr[index] = ele.charAt(0).toUpperCase() + ele.substr(1)
});
return arr;
};
console.info(String.prototype.toJadenCase("Hi there how are you"));
Не рекомендуется добавлять методы в Prototype
, вы можете просто написать функцию и использовать ее.
const str = "Hi there how are you?";
const changeFirstChar = (str) => str[0].toUpperCase() + str.substr(1)
const toJadenCase = function(st) {
let arr = st.split(" ");
return arr.map(e => changeFirstChar(e))
};
console.info(toJadenCase("Hi there how are you"));
//if you need output as string
console.info(toJadenCase("Hi there how are you").join(' '));
Вы должны изменить
arr[index][0] = ele.charAt(0).toUpperCase();
В настоящее время вы заменяете всю строку вindex
позиции в массиве. Скорее замените только первую букву