Как сделать первую букву строки заглавной в JavaScript? - PullRequest
3412 голосов
/ 22 июня 2009

Как сделать первую букву строки заглавной, но не изменить регистр других букв?

Например:

  • "this is a test" -> "This is a test"
  • "the Eiffel Tower" -> "The Eiffel Tower"
  • "/index.html" -> "/index.html"

Ответы [ 83 ]

3 голосов
/ 30 апреля 2018

Вот хорошая и более чистая версия;

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

Результаты:

это тест -> это тест

3 голосов
/ 23 ноября 2016
function cap(input) {
    return input.replace(/[\.\r\n\t\:\;\?\!]\W*(\w)/g, function(match, capture) {
                  // for other sentences in text
                  return match.toUpperCase();
                 }).replace(/^\W*\w/, function(match, capture) {
                 // for first sentence in text
                  return match.toUpperCase();
                 });;
}

var a = "hi, dear user. it is a simple test. see you later!\r\nbye";
console.log(cap(a));
//output: Hi, dear user. It is a simple test. See you later!
//Bye
3 голосов
/ 26 декабря 2017

Anotehr способ с использованием RamdaJs, способ функционального программирования

firstCapital(str){
    const fn= p=> R.toUpper(R.head(p))+R.tail(p);
    return fn(str);
  }

С несколькими словами в строке

firstCapitalAllWords(str){
    const fn = p=> R.toUpper(R.head(p))+R.tail(p);
    return R.map(fn,R.split(' ',str)).join(' ');
}
3 голосов
/ 16 сентября 2016

Если в вашем проекте Lodash, используйте upperFirst.

2 голосов
/ 14 февраля 2018
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));
2 голосов
/ 22 января 2018

Однако то, что вы можете, не означает, что вы должны это делать. Требуется ECMAScript 6, так как в коде используется деструктуризация массива.

const capitalizeFirstLetter = s => {
  const type = typeof s;
  if (type !== "string") {
    throw new Error(`Expected string, instead received ${type}`);
  }

  const [firstChar, ...remainingChars] = s;

  return [firstChar.toUpperCase(), ...remainingChars].join("");
};
2 голосов
/ 21 ноября 2013

Функция принимает 2 аргумента: start - начальный индекс; длина - длина подстроки в заглавные буквы

    String.prototype.subUpper = function () {
        var result = this.toString();
        var start = 0;
        var length = 1;
        if (arguments.length > 0) {
            start = arguments[0];
            if (start < this.length) {
                if (arguments.length > 1) { length = arguments[1]; }
                if (start + length > this.length) {
                    length = this.length - start;
                }
                var startRest = start + length;
                var prefix = start > 0 ? this.substr(0, start) : String.empty;
                var sub = this.substr(start, length);
                var suffix = this.substr(startRest, this.length - startRest);
                result = prefix + sub.toUpperCase() + suffix;
            }
        }
        return result;
    };
2 голосов
/ 24 декабря 2014

Используйте этот модуль Node.js, пакет http://stringjs.com/, чтобы использовать заглавную строку:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
2 голосов
/ 03 мая 2016

Этот допустит возможные пробелы в начале и не пропустит цель первой буквы в строке. Следовательно, это может улучшить уже хорошие решения, доступные в потоке.

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

! Но, вызовет «мягкую» ошибку, если выполняется с пустой строкой. Чтобы избежать этой возможной ошибки или ненужной обработки пустой строки или числа, может использоваться троичная условная защита:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;
2 голосов
/ 07 августа 2014

Вот что я использую неукоснительно:

function capitalizeMe(str,force){
    str=force ? str.toLowerCase() : str;  
    return str.replace(/(\b)([a-zA-Z])/g,
    function(firstLetter){
        return firstLetter.toUpperCase();
    });
}

var firstName = capitalizeMe($firstName.val());
...