첫 글자를 대문자로하고 나머지 문자열을 소문자로 바꾸는 방법
Aug 20 2020
문장에서 첫 단어의 첫 글자 만 대문자로 바꾸려고합니다.
이것은 tsx 파일의 데이터입니다 {this.text ({id : downloadPriceHistory
, defaultMessage : 'Download Price History'})} 위에 표시된 ID는 다양한 형태로 API에 전송할 수있는 데이터베이스에서 가져옵니다.
이 논리를 아래에서 사용하려고했습니다.
export function titleCase(string) {
string = 'hello World';
const sentence = string.toLowerCase().split('');
for (let i = 0; i < sentence.length; i++) {
sentence[i] = sentence[i][0].toUpperCase() + sentence[i];
}
return sentence;
}
예를 들어 입력 "Download Price History"
의 경우 결과는이어야합니다 "Download price history"
.
답변
4 iota Aug 20 2020 at 18:36
첫 글자 만 대문자로하고 소문자로 변환 된 나머지 문자열에 연결하면됩니다.
function titleCase(string){
return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
console.log(titleCase('Download Price History'));
이것은 또한 설정하여 CSS로 수행 할 수 있습니다 text-transform
에 lowercase
전체 요소와 사용 ::first-letter
집합에 의사 요소 text-transform
에를 uppercase
.
.capitalize-first {
text-transform: lowercase;
}
.capitalize-first::first-letter {
text-transform: uppercase;
}
<p class="capitalize-first">Download Price History</p>
2 Manas Aug 20 2020 at 18:35
try-나머지 문자열도 소문자로 만듭니다.
export function titleCase(string) {
return string[0].toUpperCase() + string.substr(1).toLowerCase()
}
1 codythecoder Aug 20 2020 at 18:41
전체 문자열을 소문자로만 쓰고 대문자는 새 문자열의 첫 글자 만 사용하지 않는 이유는 무엇입니까?
function titleCase(string) {
let sentence = string.toLowerCase();
let titleCaseSentence = sentence.charAt(0).toUpperCase() + sentence.substring(1, sentence.length);
return titleCaseSentence;
}
(또한 첫 번째 줄을 사용하여 함수에 대한 매개 변수를 지 웁니다.)
string = 'hello World';
1 MuriloGóesdeAlmeida Aug 20 2020 at 18:43
내 제안은 문자열의 첫 번째 요소를 가져와 대문자로 입력하고 나머지 문자열을 가져 와서 소문자 기능을 적용하는 것입니다.
titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
1 Constantin Aug 20 2020 at 18:36
CSS 사용 :
p {
text-transform: lowercase;
}
p::first-letter {
text-transform: uppercase
}
JS 사용 :
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1).toLowercase();