programing

Lodash 타이틀 케이스 (모든 단어의 대문자 첫 글자)

easyjava 2023. 9. 26. 22:40
반응형

Lodash 타이틀 케이스 (모든 단어의 대문자 첫 글자)

lodash 문서 및 기타 Stack Overflow 질문을 살펴보고 있습니다. 이 작업을 수행하는 여러 네이티브 자바스크립트 방법이 있지만 정규식을 사용하거나 새 함수를 정의할 필요가 없도록 순수 lodash 함수(또는 최소한 기존 프로토타입 함수)를 사용하여 문자열을 제목 케이스로 변환할 수 있는 방법이 있습니까?

예.

This string ShouLD be ALL in title CASe

될 것입니다

This String Should Be All In Title Case

이 작업은 다음과 같은 작은 수정을 통해 수행할 수 있습니다.

_.startCase(_.toLower(str));

console.log(_.startCase(_.toLower("This string ShouLD be ALL in title CASe")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

_.startCase(_.camelCase(str))

사용자가 생성하지 않은 텍스트의 경우 허용된 답변보다 더 많은 경우를 처리합니다.

> startCase(camelCase('myString'))
'My String'
> startCase(camelCase('my_string'))
'My String'
> startCase(camelCase('MY_STRING'))
'My String'
> startCase(camelCase('my string'))
'My String'
> startCase(camelCase('My string'))
'My String'

Lodash 버전 4와 함께.

_.upperFirst(_.toLower(str))

'This string ShouLD be ALL in title CASe'
  .split(' ')
  .map(_.capitalize)
  .join(' ');

이 질문에 대한 대답은 엇갈립니다.일부에서는 사용을 권장하고 있습니다._.upperFirst권하는 사이에_.startCase.

그들 사이의 차이를 알아보세요.

i)_.upperFirst문자열의 첫 글자를 변환하고 문자열은 한 단어 또는 여러 단어일 수 있지만 문자열의 첫 글자만 대문자로 변환됩니다.

_.upperFirst('jon doe')

출력:

Jon doe

https://lodash.com/docs/4.17.10#upperFirst 문서를 확인합니다.

ii)_.startCase당신의 문자열 안에 있는 모든 단어의 첫 글자를 변형시킬 것입니다.

_.startCase('jon doe')

출력:

Jon Doe

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

이는 제가 사용한 사례에서 테스트해 본 바로는 가장 깨끗하고 유연한 구현입니다.

import { capitalize, map } from "lodash";

const titleCase = (str) => map(str.split(" "), capitalize).join(" ");

// titleCase("ALFRED NÚÑEZ") => "Alfred Núñez"
// titleCase("alfred núñez") => "Alfred Núñez"
// titleCase("AlFReD nÚñEZ") => "Alfred Núñez"
// titleCase("-") => "-"

출처: https://github.com/lodash/lodash/issues/3383#issuecomment-430586750

'JHON&JOHN C/O DR. BLah'.replace(/\w+/g, _.capitalize);

결과:

'Jhon&John C/O Dr. Blah'

Lodash 메서드만 사용하고 내장 메서드는 사용하지 않는 방법이 있습니다.

_.reduce(_.map(_.split("Hello everyOne IN the WOrld", " "), _.capitalize), (a, b) => a + " " + b)

아래 코드는 완벽하게 작동합니다.

var str = "TITLECASE";
_.startCase(str.toLowerCase());

이것은 lodash 만으로 할 수 있습니다.

properCase = string =>
        words(string)
            .map(capitalize)
            .join(' ');

const proper = properCase('make this sentence propercase');

console.log(proper);
//would return 'Make This Sentence Propercase'
 var s = 'This string ShouLD be ALL in title CASe';
 _.map(s.split(' '), (w) => _.capitalize(w.toLowerCase())).join(' ')

제가 놓치지 않는 한, lodash에는 고유의 소문자/대소문자 방법이 없습니다.

const titleCase = str =>
  str
    .split(' ')
    .map(str => {
      const word = str.toLowerCase()
      return word.charAt(0).toUpperCase() + word.slice(1)
    })
    .join(' ')

지도 기능을 분할하여 별도의 단어를 수행할 수도 있습니다.

@4castle의 대답처럼 간결하지는 않지만, 그럼에도 불구하고 설명적이고 로다시 가득 찬...

var basicTitleCase = _
    .chain('This string ShouLD be ALL in title CASe')
    .toLower()
    .words()
    .map(_.capitalize)
    .join(' ')
    .value()

console.log('Result:', basicTitleCase)
console.log('Exact Match:' , basicTitleCase === 'This String Should Be All In Title Case')
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

여기 제 사용 사례에 대한 또 다른 해결책이 있습니다: "악마의 백본"

간단히:

function titleCase (str) {
  return _.map(str.split(' '), _.upperFirst).join(' ');
}

startCase를 사용하면 아포스트로피가 제거되기 때문에 그 한계를 극복해야 했습니다.다른 해결책들은 꽤 복잡해 보였습니다.저는 깨끗하고 이해하기 쉬워서 좋습니다.

단순히 low dash 대문자화 방법을 사용할 수 있습니다. 문자열의 첫 번째 문자를 대문자로, 나머지를 소문자로 변환합니다.https://lodash.com/docs/ #자본화

const str = 'titlecase this string ';
_.capitalize(str); //Titlecase This String

lodash 4를 사용하면 _.capitalize를 사용할 수 있습니다.

_.capitalize('JOHN')"다의을 반환합니다.

자세한 내용은 https://lodash.com/docs/4.17.5#capitalize 참조

언급URL : https://stackoverflow.com/questions/38084396/lodash-title-case-uppercase-first-letter-of-every-word

반응형