688

文字列をタイトルケースに変換する簡単な方法はありますか? 例えばjohn smith​​となりJohn Smithます。私はJohn Resig's solution のような複雑なものを探しているのではなく、(うまくいけば) ある種のワンライナーまたはツーライナーを探しています。

4

66 に答える 66

882

これを試して:

function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}
<form>
  Input:
  <br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
  <br />Output:
  <br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>

于 2008-10-13T08:18:26.823 に答える
246

CSS ソリューションがニーズを満たしている場合は、テキスト変換CSS スタイルをコントロールに適用できます。

text-transform: capitalize;

これは次のように変換されることに注意してください:
hello worldto Hello World
HELLO WORLDto HELLO WORLD(変化なし)
emily-jane o'briento Emily-jane O'brien(不正解)
Maria von Trappto Maria Von Trapp(不正解)

于 2010-06-16T14:58:43.533 に答える
219

Greg Dean の関数を適応させた、もう少しエレガントな方法:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

次のように呼び出します。

"pascal".toProperCase();
于 2011-04-07T00:14:49.800 に答える
154

これが私のバージョンです。IMOは理解しやすく、エレガントでもあります。

const str = "foo bar baz";
const newStr = str.split(' ')
   .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
   .join(' ');
console.log(newStr);

于 2014-03-05T09:07:37.420 に答える
113

これは、タイトルの大文字と小文字に変換するだけでなく、定義された頭字語を大文字として、マイナーワードを小文字として保持する私の関数です。

String.prototype.toTitleCase = function() {
  var i, j, str, lowers, uppers;
  str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

例えば:

"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
于 2011-06-25T01:04:11.960 に答える
55

私は他の答えよりも次のことを好みます。各単語の最初の文字のみが一致し、大文字になります。コードが単純になり、読みやすくなり、バイト数が少なくなります。頭字語の歪みを防ぐために、既存の大文字を保持します。toLowerCase()ただし、いつでも最初に文字列を呼び出すことができます。

function title(str) {
  return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

'my string'.toTitle()これを文字列プロトタイプに追加すると、次のことが可能になります。

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

例:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

console.log('all lower case ->','all lower case'.toTitle());
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());

于 2017-10-26T16:36:48.673 に答える
31

すぐtoLowerCaseに文字列を取得し、次にtoUpperCase各単語の最初の文字のみを取得できます。非常にシンプルな 1 ライナーになります。

function titleCase(str) {
  return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());
}

console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));

于 2016-10-18T15:09:38.183 に答える
20

参考のために正規表現を使用せずに:

String.prototype.toProperCase = function() {
  var words = this.split(' ');
  var results = [];
  for (var i = 0; i < words.length; i++) {
    var letter = words[i].charAt(0).toUpperCase();
    results.push(letter + words[i].slice(1));
  }
  return results.join(' ');
};

console.log(
  'john smith'.toProperCase()
)

于 2011-12-19T16:25:25.267 に答える
16

これらのフィラー ワードが心配な場合に備えて、大文字にしないものをいつでも関数に伝えることができます。

/**
 * @param String str The text to be converted to titleCase.
 * @param Array glue the words to leave in lowercase. 
 */
var titleCase = function(str, glue){
    glue = (glue) ? glue : ['of', 'for', 'and'];
    return str.replace(/(\w)(\w*)/g, function(_, i, r){
        var j = i.toUpperCase() + (r != null ? r : "");
        return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
    });
};

これがお役に立てば幸いです。

編集

先頭のグルー ワードを処理したい場合は、もう 1 つの変数を使用してこれを追跡できます。

var titleCase = function(str, glue){
    glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
    var first = true;
    return str.replace(/(\w)(\w*)/g, function(_, i, r) {
        var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
        var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
        first = false;
        return result;
    });
};
于 2010-11-13T05:17:59.487 に答える
14

上記のソリューションで使用されている正規表現が混乱している場合は、次のコードを試してください。

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}
于 2016-02-28T10:16:42.320 に答える
14

文法的に正しい答えが必要な場合:

この回答では、「of」、「from」などの前置詞が考慮されています。出力は、論文に表示されると予想される編集スタイルのタイトルを生成します。

toTitleCase 関数

ここにリストされている文法規則を考慮した関数。この関数は、空白を統合し、特殊文字を削除します (必要に応じて正規表現を変更します)。

const toTitleCase = (str) => {
  const articles = ['a', 'an', 'the'];
  const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
  const prepositions = [
    'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
    'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
  ];

  // The list of spacial characters can be tweaked here
  const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
  const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
  const normalizeStr = (str) => str.toLowerCase().trim();
  const shouldCapitalize = (word, fullWordList, posWithinStr) => {
    if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
      return true;
    }

    return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
  }

  str = replaceCharsWithSpace(str);
  str = normalizeStr(str);

  let words = str.split(' ');
  if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
    words = words.map(w => capitalizeFirstLetter(w));
  }
  else {
    for (let i = 0; i < words.length; i++) {
      words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
    }
  }

  return words.join(' ');
}

正確性を確認するための単体テスト

import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';

describe('toTitleCase', () => {
  it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
    expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
    expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
    expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
  });

  it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
    expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
    expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
    expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
  });

  it('Replace special characters with space', function(){
    expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
    expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
  });

  it('Trim whitespace at beginning and end', function(){
    expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
  });

  it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
    expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
    expect(toTitleCase('the  three Musketeers  And plus ')).to.equal('The Three Musketeers and Plus');
  });
});

提供された文字列からかなりの特殊文字を削除していることに注意してください。プロジェクトの要件に対応するには、正規表現を微調整する必要があります。

于 2017-10-16T16:17:08.053 に答える
11

ES6

str.split(' ')
   .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
   .join(' ')

そうしないと

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')
于 2016-10-27T15:52:59.370 に答える
11

"McDonald" や "MacDonald" や "O'Toole" や "D'Orazio" などの姓 (タイトル ケースではありません) を処理できるこの関数を作成しました。ただし、「van」または「von」を含むドイツ語またはオランダ語の名前は処理されません。これらはしばしば小文字です...「de」も「Robert de Niro」のように小文字であることが多いと思います。これらはまだ対処する必要があります。

function toProperCase(s)
{
  return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
          function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}
于 2010-02-03T22:22:57.930 に答える
8
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

動作するようです...上記の「ザ・クイック・ブラウン、キツネ? /jumps/ ^over^ the 怠惰な犬...」および「C:/program files/some vendor/their 2nd application/a」でテスト済みfile1.txt".

2nd ではなく 2nd が必要な場合は、 に変更できます/([a-z])(\w*)/g

最初の形式は次のように簡略化できます。

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
于 2008-10-13T08:17:39.070 に答える
8

これらの回答のほとんどは、単語境界メタ文字 (\b) を使用する可能性を無視しているようです。それを利用したGreg Deanの答えの短いバージョン:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

Jim-Bob のようなハイフン付きの名前でも機能します。

于 2014-07-16T14:59:34.077 に答える
6
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
于 2019-06-21T08:30:25.190 に答える
6

これを試して

String.prototype.toProperCase = function(){
    return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, 
        function($1){
            return $1.toUpperCase();
        }
    );
};

var str = 'john smith';
str.toProperCase();
于 2012-05-16T19:05:54.217 に答える
5

これは、アクセント付きの文字 (フランス語にとって重要です!) を処理し、下位例外の処理のオン/オフを切り替えることができる私の関数です。それが役立つことを願っています。

String.prototype.titlecase = function(lang, withLowers = false) {
    var i, string, lowers, uppers;

    string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }).replace(/Mc(.)/g, function(match, next) {
        return 'Mc' + next.toUpperCase();
    });

    if (withLowers) {
        if (lang == 'EN') {
            lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
        }
        else {
            lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
        }
        for (i = 0; i < lowers.length; i++) {
            string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                return txt.toLowerCase();
            });
        }
    }

    uppers = ['Id', 'R&d'];
    for (i = 0; i < uppers.length; i++) {
        string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
    }

    return string;
}
于 2016-12-11T16:36:57.053 に答える
5

/\S+/g分音記号をサポートするために使用します。

function toTitleCase(str) {
  return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}

console.log(toTitleCase("a city named örebro")); // A City Named Örebro

ただし、「s unshine ( yellow)」⇒「s unshine ( yellow )」

于 2016-06-20T20:31:25.903 に答える
4

「lewax00」ソリューションを使用して、スペースで始まる「w」または単語を開始する「w」を強制するこの単純なソリューションを作成しましたが、余分な中間スペースを削除することはできません。

"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });

その結果が「ソフィア・ベルガラ」です。

于 2014-09-30T18:52:16.307 に答える
2

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

Lodashライブラリを使用..!! より信頼できる

_.capitalize('FRED'); => 'Fred'
于 2019-01-09T07:15:56.770 に答える
2

私のリストは、3 つのクイック検索に基づいています。1 つは大文字にしない単語のリスト用で、もう 1 つは前置詞の完全なリスト用です。

ある最後の検索では、5 文字以上の前置詞は大文字にする必要があるという提案がありました。これは私が気に入ったものです。私の目的は非公式の使用です。私は彼らの「なし」を残しました。

そのため、頭字語、タイトルの最初の文字、およびほとんどの単語の最初の文字を大文字にします。

caps-lock で単語を処理するためのものではありません。それらを放っておきたかったのです。

function camelCase(str) {
  return str.replace(/((?:^|\.)\w|\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\b)\w)/g, function(character) {
  return character.toUpperCase();
})}
    
console.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));

于 2020-04-09T14:16:12.797 に答える
1

短くはありませんが、学校での最近の課題で私が思いついたのは次のとおりです。

var myPoem = 'What is a jQuery but a misunderstood object?'
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?

  //code here
var capitalize = function(str) {
  var strArr = str.split(' ');
  var newArr = [];
  for (var i = 0; i < strArr.length; i++) {
    newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))
  };
  return newArr.join(' ')  
}

var fixedPoem = capitalize(myPoem);
alert(fixedPoem);

于 2015-04-21T00:28:22.017 に答える
1

堅牢な関数型プログラミングの方法Title Case Function

Exaplin バージョン

function toTitleCase(input){
    let output = input
        .split(' ')  // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
        .map((letter) => {
            let firstLetter = letter[0].toUpperCase() // H , a , Y  => H , A , Y
            let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
            return firstLetter + restLetters // conbine together
        })
        .join(' ') //['How' 'Are' 'You'] => 'How Are You'
    return output
}

実装バージョン

function toTitleCase(input){
    return input
            .split(' ')
            .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
            .join(' ') 
}

toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
于 2016-10-17T15:27:14.907 に答える
1

シンプルなキャッシングを備えた、よりシンプルでパフォーマンスの高いバージョン。

  var TITLE_CASE_LOWER_MAP = {
    'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,
    'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1
  };

  // LEAK/CACHE TODO: evaluate using LRU.
  var TITLE_CASE_CACHE = new Object();

  toTitleCase: function (title) {
    if (!title) return null;

    var result = TITLE_CASE_CACHE[title];
    if (result) {
      return result;
    }

    result = "";
    var split = title.toLowerCase().split(" ");
    for (var i=0; i < split.length; i++) {

      if (i > 0) {
        result += " ";
      }

      var word = split[i];
      if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {
        word = word.substr(0,1).toUpperCase() + word.substr(1);
      }

      result += word;
    }

    TITLE_CASE_CACHE[title] = result;

    return result;
  },

于 2015-09-09T17:12:16.447 に答える
1

Greg Dean のソリューションのプロトタイプ ソリューション:

String.prototype.capitalize = function() {
  return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
于 2015-08-06T20:19:40.593 に答える
1

this is a test--->This Is A Test

function capitalize(str) {

  const word = [];

  for (let char of str.split(' ')) {
    word.push(char[0].toUpperCase() + char.slice(1))
  }

  return word.join(' ');

}

console.log(capitalize("this is a test"));

于 2018-07-15T06:55:06.760 に答える
1

いくつかの素晴らしい答えがありましたが、多くの人が正規表現を使用して単語を見つけましたが、何らかの理由で、正規表現を使用して最初の文字を置き換える人は誰もいません。説明のために、長い解決策と短い解決策を提供します。

長い解決策(より説明的)。正規表現[^\s_\-/]*を使用すると、文中のすべての単語を見つけることができます。その後、正規表現.を使用して、単語の最初の文字に一致させることができます。これらの両方に replace の正規表現バージョンを使用すると、次のようにソリューションを変更できます。

function toUpperCase(str) { return str.toUpperCase(); }
function capitalizeWord(word) { return word.replace(/./, toUpperCase); }
function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); }

console.log(capitalize("hello world")); // Outputs: Hello World

同じことを行う単一の関数の場合、replace次のように呼び出しをネストします。

function capitalize(sentence) {
  return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) {
    return word.replace(/./, function (ch) { return ch.toUpperCase(); } );
  } );
}

console.log(capitalize("hello world")); // Outputs: Hello World

于 2018-03-21T04:33:49.100 に答える
1

問題に対する私のシンプルで簡単なバージョン:

    function titlecase(str){
    var arr=[];  
    var str1=str.split(' ');
    for (var i = 0; i < str1.length; i++) {
    var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
    arr.push(upper);
     };
      return arr.join(' ');
    }
    titlecase('my name is suryatapa roy');
于 2016-05-02T20:38:11.290 に答える
0

John Resig のソリューションと同じくらいフル機能ですが、ワンライナーとして: (この github プロジェクトに基づく)

function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};

console.log( toTitleCase( "ignores mixed case words like iTunes, and allows AT&A and website.com/address etc..." ) );
于 2012-09-21T15:28:28.360 に答える
0
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;
}
于 2015-12-13T14:06:06.223 に答える
0

ミックスに追加する別のバージョン。これは、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);
};
于 2016-07-28T15:08:41.560 に答える
0

Another approach to achieve something similar can be as follows.

formatName(name) {
    let nam = '';
    name.split(' ').map((word, index) => {
        if (index === 0) {
            nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
        } else {
            nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
        }
    });
    return nam;
}
于 2018-09-15T11:30:40.777 に答える