Programming

JavaScript를 사용하여 문자열을 제목으로 변환

procodes 2020. 2. 12. 23:45
반응형

JavaScript를 사용하여 문자열을 제목으로 변환


문자열을 제목 대소 문자로 변환하는 간단한 방법이 있습니까? 예를 john smith하게된다 John Smith. 나는 John Resig의 솔루션 과 같은 복잡한 것을 찾고 있지 않습니다 . 단지 희망적으로 일종의 1-2 라이너입니다.


이 시도:

    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>


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();

텍스트 변환 CSS 스타일을 컨트롤 에 적용하십시오 .

예 : (text-transform: capitalize);

꼭 필요한 경우에만 JS 접근 방식을 사용하십시오.


여기 내 버전이 있습니다. IMO 이해하기 쉽고 우아합니다.

var str = "foo bar baz"

console.log(

str.split(' ')
   .map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
   .join(' ')

)
// returns "Foo Bar Baz"


다음은 제목으로 변환하지만 정의 된 약어를 ​​대문자로, 작은 단어를 소문자로 유지하는 함수입니다.

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:"

다른 답변보다 다음을 선호합니다. 각 단어의 첫 글자 만 일치하고 대문자를 사용합니다. 더 간단한 코드, 더 읽기 쉽고 바이트가 적습니다. 약어가 왜곡되는 것을 방지하기 위해 기존 대문자를 유지합니다. 그러나 항상 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.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()
)


필러 단어가 걱정되는 경우 항상 대문자로 표시하지 말아야 할 것을 함수에 알려줄 수 있습니다.

/**
 * @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();
    });
};

이것이 도움이되기를 바랍니다.

편집하다

선행 접착제 단어를 처리하려면 변수를 하나 더 추가하십시오.

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;
    });
};

위의 솔루션에 사용 된 정규 표현식이 혼란 스러우면이 코드를 사용해보십시오.

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}

이것은 하나의 단어 문자열에서만 작동하지만 그것이 내가 필요한 것입니다.

'string'.replace(/^[a-z]/, function (x) {return x.toUpperCase()}) // String

JSFiddle : https://jsfiddle.net/simo/gou2uhLm/


당신은 즉시 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'));


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 : / 프로그램 파일 / 일부 공급 업체 / 두 번째 응용 프로그램 / a file1.txt ".

2nd 대신 2Nd를 원하면로 변경할 수 있습니다 /([a-z])(\w*)/g.

첫 번째 양식은 다음과 같이 단순화 할 수 있습니다.

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}

"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(); });
}

이 시도

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();

가장 짧은 방법으로 시도하십시오.

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());

ES 6

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(' ')

이러한 답변의 대부분은 단어 경계 메타 문자 (\ b)를 사용할 가능성을 무시하는 것 같습니다. 그것을 사용하는 그렉 딘의 대답의 짧은 버전 :

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

Jim-Bob과 같은 하이픈 이름에도 적용됩니다.


가장 간단한 방법은 CSS를 사용하는 것입니다.

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}

/\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 빛나기 ( y ellow)"⇒ " S 빛나기 ( y ellow)"


코드에서 타사 라이브러리를 사용할 수 있다면 lodash에는 도우미 기능이 있습니다.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'


"lewax00"솔루션을 사용하면서 나는 공백으로 시작하는 "w"또는 단어를 시작하는 "w"로 강제하지만 추가 중간 공간을 제거 할 수없는이 간단한 솔루션을 만들었습니다.

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

결과는 "Sofía Vergara"입니다.


다음은 CSS를 사용하는 또 다른 솔루션입니다 (변환하려는 텍스트가 대문자 인 경우 자바 스크립트).

html

<span id='text'>JOHN SMITH</span>

js

var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();

CSS

#text{text-transform:capitalize;}

"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())

다음은 악센트 문자 (프랑스어에 중요합니다)를 처리하고 하위 예외 처리를 켜거나 끌 수있는 내 기능입니다. 희망이 도움이됩니다.

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;
}

정규식이 두려운 사람 (lol) :

function titleCase(str)
{
    var words = str.split(" ");
    for ( var i = 0; i < words.length; i++ )
    {
        var j = words[i].charAt(0).toUpperCase();
        words[i] = j + words[i].substr(1);
    }
    return words.join(" ");
}


우리는 사무실에서 다시 토론을 해 왔으며 사람들이 원하는 방식으로 이름을 입력하는 방식을 자동으로 수정하려고하면 가능한 문제가 있다고 생각합니다.

우리는 서로 다른 유형의 자동 대문자가 다른 몇 가지 경우를 생각해 냈는데 , 이는 영어 이름만을위한 것이며 각 언어마다 고유 한 복잡성이 있습니다.

각 이름의 첫 글자를 대문자로 표기 할 때의 문제 :

• IBM과 같은 약어는 입력 할 수 없으며 Ibm으로 바뀝니다.

• 맥도날드라는 이름은 맥도날드로 바뀌게되는데, 맥도날드도 마찬가지입니다.

• Marie-Tonks와 같은 이중 배럴 이름은 Marie-tonks로 바뀝니다.

• O'Connor와 같은 이름은 O'connor로 바뀔 것입니다.

대부분의 경우 사용자 지정 규칙을 작성하여 처리 할 수 ​​있지만 여전히 이전과 같이 약어 문제가 있으며 새로운 문제가 발생합니다.

• MacDonald와 같은 Mac에서 이름을 수정하는 규칙을 추가하면 Macy와 같은 구분 이름이 MacY로 바뀝니다.

우리가 틀린 적이없는 유일한 해결책은 DBS가 사용하는 것처럼 보이는 무차별 강제 방법 인 모든 문자를 대문자로 쓰는 것입니다.

따라서 프로세스를 자동화하려면 모든 단일 이름과 단어를 사전없이 사용하는 것이 불가능합니다. 어떻게해야하는지, 모든 것을 포괄하는 규칙이 없다면 사용하지 마십시오. 사용자를 성가 시게하고 자신의 이름을 올바르게 입력하려는 사람들에게 다른 곳으로 이동하도록 유도합니다.


여기에 나열된toTitleCase 문법 규칙을 고려한 강력한 기능이 필요했기 때문에 내 답변을 추가하고 싶었 습니다 (Google 권장 기사). 입력 문자열의 길이에 따라 다양한 규칙이 있습니다. 아래는 기능 + 단위 테스트입니다.

이 기능은 또한 공백을 통합하고 특수 문자를 제거합니다 (필요에 따라 정규식 수정)

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');
  });
});

제공된 문자열에서 꽤 많은 특수 문자를 제거하고 있습니다. 프로젝트 요구 사항을 해결하려면 정규식을 조정해야합니다.


이것은 FreeCodeCamp의 Bonfire "Title Case" 솔루션을 기반으로 합니다. 먼저 주어진 문자열을 모두 소문자로 변환 한 다음 공백을 처리하는 모든 문자를 대문자로 변환해야합니다.

정규식을 사용하지 않고 :

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}

문제에 대한 나의 간단하고 쉬운 버전 :

    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');

먼저 공백 string으로 나눠서 배열 로 변환하십시오 .

var words = str.split(' ');

그런 다음 array.map 을 사용하여 대문자로 된 새 배열을 만듭니다.

var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});

그런 다음 공백으로 새 배열을 결합 하십시오.

capitalized.join(" ");

function titleCase(str) {
  str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
  var words = str.split(" ");

  var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
  });
  return capitalized.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

노트:

물론 이것은 단점이 있습니다. 모든 단어의 첫 글자 만 대문자로 표기합니다. 즉, 공백으로 구분 된 모든 문자열을 1 단어로 취급합니다.

아마도 당신은 가지고 있습니다 :

str = "I'm a little/small tea pot";

이것은 생산할 것이다

나는 작은 / 작은 차 남비

예상과 비교

나는 작은 / 작은 차 남비입니다

이 경우 Regex 및 .replace사용 하면 트릭을 수행합니다.

ES6 사용시 :

const capitalize = str => str.length
  ? str[0].toUpperCase() +
    str.slice(1).toLowerCase()
  : '';

const escape = str => str.replace(/./g, c => `\\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
  let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
  
  return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );

또는 ES6 없이 :

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}

function titleCase(str) {
  return str.replace(/[^\ \/\-\_]+/g, capitalize);
}

console.log(titleCase("hello/hi world"));

참고 URL : https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript



반응형