Преобразовать строку в заголовок с помощью JavaScript - PullRequest
477 голосов
/ 13 октября 2008

Есть ли простой способ преобразования строки в регистр заголовков? Например. john smith становится John Smith. Я не ищу ничего сложного, такого как решение Джона Резига , просто (надеюсь) какой-то одно- или двухслойный.

Ответы [ 49 ]

0 голосов
/ 05 сентября 2018

Метод использования уменьшить

function titleCase(str) {
  const arr = str.split(" ");
  const result = arr.reduce((acc, cur) => {
    const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();
    return acc += `${newStr} `
  },"")
  return result.slice(0, result.length-1);
}
0 голосов
/ 28 июля 2016

Просто еще одна версия для добавления в микс. Это также проверит, является ли string.length 0:

String.prototype.toTitleCase = function() {
    var str = this;
    if(!str.length) {
        return "";
    }
    str = str.split(" ");
    for(var i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
    }
    return (str.length ? str.join(" ") : str);
};
0 голосов
/ 07 июля 2015

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

var stringToConvert = 'john';
stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');
console.log(stringToConvert);
0 голосов
/ 08 июня 2015
function toTitleCase(str) {
  var strnew = "";
  var i = 0;

  for (i = 0; i < str.length; i++) {
    if (i == 0) {
      strnew = strnew + str[i].toUpperCase();
    } else if (i != 0 && str[i - 1] == " ") {
      strnew = strnew + str[i].toUpperCase();
    } else {
      strnew = strnew + str[i];
    }
  }

  alert(strnew);
}

toTitleCase("hello world how are u");
0 голосов
/ 06 февраля 2016
String.prototype.capitalize = function() {
    return this.toLowerCase().split(' ').map(capFirst).join(' ');
    function capFirst(str) {
        return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
    }
}

Использование:

"hello world".capitalize()
0 голосов
/ 13 декабря 2015
function titleCase(str) {
    str = str.toLowerCase();

    var strArray = str.split(" ");


    for(var i = 0; i < strArray.length; i++){
        strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);

    }

    var result = strArray.join(" ");

    //Return the string
    return result;
}
0 голосов
/ 09 января 2019

https://lodash.com/docs/4.17.11#capitalize

Используйте библиотеку Lodash .. !! Надежнее

_.capitalize('FRED'); => 'Fred'
0 голосов
/ 05 февраля 2019

Джон Смит -> Джон Смит

'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );
0 голосов
/ 21 июня 2017

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

var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");

// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
    var newSentence = true;
    return this.split(/\s+/).map(function(word) {
        if (word == "") { return; }
        var canCapitalise = true;
        // Get the pos of the first alpha char (word might start with " or ')
        var firstAlphaCharPos = word.search(/\w/);
        // Check for uppercase char that is not the first char (might be acronym or all caps)
        if (word.search(/[A-Z]/) > 0) {
            canCapitalise = false;
        } else if (stopWordsArray.indexOf(word) != -1) {
            // Is a stop word and not a new sentence
            word.toLowerCase();
            if (!newSentence) {
                canCapitalise = false;
            }
        }
        // Is this the last word in a sentence?
        newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
        return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
    }).join(' ');
}

// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());

/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
...