변수의 대문자 첫번째 문자
저는 인터넷으로 찾아봤지만 저를 도와줄 만한 것을 찾을 수가 없습니다.각 단어의 첫 글자를 변수 안에 넣으려고 합니다.
지금까지 시도해 본 결과:
toUpperCase();
그리고 운이 없었어요. 모든 글자를 앞에 놓았기 때문이죠.
.replace 함수를 사용하여 단어를 시작하는 소문자를 대문자로 바꿉니다.
var str = "hello, world!";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Hello, World!"
만약 당신이 a-z가 아닌 단어 문자를 다루고 있다면, 다음의 (더 복잡한) 정규 표현식이 당신의 목적에 더 적합할 것입니다.
var str = "петр данилович björn über ñaque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Björn Über Ñaque Αλφα"
훨씬 더 쉬운 방법:
$('#test').css('textTransform', 'capitalize');
라파엘 허스코비치가 나를 올바른 길로 인도한 공로를 인정해야 합니다.당신들이 제안하는 것보다 훨씬 간단합니다.
http://phpjs.org/functions/ucwords:569 은 좋은 예시를 가지고 있습니다.
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
(간단한 설명을 위해 출처의 기능 설명을 omitted합니다.자세한 내용은 링크된 출처 참조)
EDIT: 이 함수는 문자열의 첫 번째 문자(질문 제목이 질문하는 대로)가 아니라 각 단어의 첫 번째 문자를 대문자로 쓴다는 점에 유의하십시오.
순수 자바스크립트 솔루션(jQuery 없음)은 다음과 같습니다.
function capitalize(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
console.log(capitalize('hello world'));
부분 문자열()과 대문자()를 사용하여 첫 번째 문자를 뽑아 대문자로 쓴 다음 문자열의 첫 번째 문자를 결과로 바꿀 수 있다고 생각합니다.
myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"
저는 그것이 당신에게 도움이 될 것이라고 생각합니다.또 다른 고려 사항은 이 데이터가 표시되는 경우 CSS 속성 "text-transform: capitalize"를 가진 클래스를 컨테이너에 추가할 수 있다는 것입니다.
다음과 같이 간단합니다.
string = 'test';
newString = string[0].toUpperCase() + string.slice(1);
alert(newString);
이를 위해서는 자바스크립트가 필요하지 않습니다.
$('#test').css('text-transform', 'capitalize');
다음과 같이 CSS로 수행합니다.
#test,h1,h2,h3 { text-transform: capitalize; }
또는 클래스로 수행하여 필요한 곳에 해당 클래스를 적용할 수 있습니다.
.ucwords { text-transform: capitalize; }
들어본적이 없습니다.substr()
?
출발자의 경우:
$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));
@FelixKling 님께 감사드립니다.
$("#test").text(function(i, text) {
return text.substr(0,1).toUpperCase() + text.substr(1);
});
Peter Olson의 답변을 바탕으로, 저는 jQuery가 없는 보다 객체 지향적인 접근법을 취했습니다.
String.prototype.ucwords = function() {
return this.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
}
alert("hello, world!".ucwords()); // Displays "Hello, World!"
예: http://jsfiddle.net/LzaYH/1/
가장 간단한 방법
let str = "hiren raiyani"
str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
사용자 정의 함수:
function capitalize(str){
return str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
}
출력 : 하이렌 라이야니
코드를 사용자 정의 함수로 사용하거나 직접 사용합니다.
var mystring = "hello World"
mystring = mystring.substring(0,1).toUpperCase() +
mystring.substring(1,mystring.length)
console.log(mystring) //gives you Hello World
var ar = 'foo bar spam egg'.split(/\W/);
for(var i=0; i<ar.length; i++) {
ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1)
}
ar.join(' '); // Foo Bar Spam Egg
당신은 PHP에 있는 ucwords의 기능으로 이 간단한 코드를 사용해 볼 수 있습니다.
function ucWords(text) {
return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');
대문자를 변경하지 않고 그대로 유지됩니다.
라파엘 허스코비치의 대답에 기반을 둔 이 솔루션은 간단한 jQuery 방법으로 'ucwords'를 부를 준비가 되었습니다.
$.extend({
ucwords : function(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
});
예:
메소드를 사용하여 호출할 수 있습니다.
var string = "this is a test";
string = $.ucwords(string); // Returns "This Is A Test"
다음 기능을 사용합니다.
const capitalize = (s) => {
if (typeof s !== 'string')
return ''
return s.charAt(0).toUpperCase() + s.slice(1)
}
capitalize('test') // 'Test'
capitalize('name') // 'Name'
사용가능text-transform: capitalize;
이 일에 있어서는
HTML
<input type="text" style="text-transform: capitalize;" />
jQuery
$(document).ready(function (){
var asdf = "WERTY UIOP";
$('input').val(asdf.toLowerCase());
});
참고: 문자열의 시각적 표현만 변경할 뿐입니다.이 문자열을 알림()하면 항상 문자열의 원래 값이 표시됩니다.
JQuery 미포함
String.prototype.ucwords = function() {
str = this.trim();
return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(s){
return s.toUpperCase();
});
};
console.log('hello world'.ucwords()); // Display Hello World
이것을 할 수 있는 많은 방법들이 있습니다!
제가 생각하기에 사람들이 잊어버린 한 가지는 문자열은 문자의 배열이라는 것입니다.따라서 문자열의 첫 글자는 배열의 '0' 요소가 됩니다.
let word = 'interesting';
console.log(word[0]);
// 'i'
이 사실을 이용하여 첫 글자를 대문자로 쓰는 가장 간단한 방법은 다음과 같습니다.
let word = 'interesting';
let titleCase = word[0].toUpperCase() + word.substr(1);
console.log(titleCase);
// 'Interesting'
...또는 함수로서:
function toTitleCase(word) {
return word[0].toUpperCase() + word.substr(1);
}
짧고 간단한 답:
let str = 'this is a string';
let result = str.replace(/\b\w/g, x => x.toUpperCase());
console.log(result); // This Is A String
자바스크립트에서 첫 글자를 대문자로 쓰는 가장 쉬운 방법
var string = "made in india";
string = string.toLowerCase().replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
alert(string);
결과:
"메이드 인디아"
나는 이 코드를 사용했습니다.
function ucword(str){
str = str.toLowerCase().replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(replace_latter) {
return replace_latter.toUpperCase();
}); //Can use also /\b[a-z]/g
return str; //First letter capital in each word
}
var uc = ucword("good morning. how are you?");
alert(uc);
제 생각에는, 그 방법은 어떤 글자들 중 첫 글자나 첫 글자 외에 다른 글자들을 변환해서는 안 됩니다.
이를 위한 제 솔루션은 다음과 같은 정규화입니다.
function capitalize( str ){
return str.replace(/^\w/, (s) => s.toUpperCase() );
}
function capitalizeAll( str ){
return str.replace(/(\b\w)/g, (s) => s.toUpperCase() );
}
let test = 'hello world';
capitalize( test ); // Hello world
capitalizeAll( test ); // Hello World
첫 글자를 대문자로 쓰기 전에 내릴 문자열입니다.
(둘 다 jQuery 구문 사용)
function CapitaliseFirstLetter(elementId) {
var txt = $("#" + elementId).val().toLowerCase();
$("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase();
}));
}
또한 전체 문자열을 대문자로 만드는 함수:
function CapitaliseAllText(elementId) {
var txt = $("#" + elementId).val();
$("#" + elementId).val(txt.toUpperCase());
}
텍스트 상자의 클릭 이벤트에 사용할 구문:
onClick="CapitaliseFirstLetter('TextId'); return false"
var str = "HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD";
str = str.replace(
/([A-Z])([A-Z]+)/g,
function (a, w1, w2) {
return w1 + w2.toLowerCase();
});
alert(str);
다음은 유니코드 안전 ucwords() 함수로, 러시아 з асс-р анцев와 같은 이중 이름과 Honoré de Balzac, D'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulaymann Ibn Dāwud 등과 같은 고귀한 이름을 추가적으로 존중합니다.
String.prototype.ucwords = function() {
return this.toLowerCase()
.replace(/(^|\s|\-)[^\s$]/g, function(m) {
return m.toUpperCase();
})
// French, Arabic and some noble names...
.replace(/\s(Of|De|Van|Von|Ibn|Из|Ван|Фон|Ибн)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd etc.
return m.toLowerCase();
})
.replace(/(^|\s)(D|Д)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / Д’Артаньян или д’Артаньян
return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase();
});
}
var country = $('#country').val();
var con = country[0].toUpperCase();
ctr = country.replace(country[0], con);
어떤 기능도 만들 필요가 없고, 그냥 jugaaraar.
HTML:
<input class="capitalize" name="Address" type="text" value="" />
jQuery가 포함된 자바스크립트:
$(".capitalize").bind("keyup change", function (e) {
if ($(this).val().length == 1)
$(this).val($(this).val().toUpperCase());
$(this).val($(this).val().toLowerCase().replace(/\s[\p{L}a-z]/g, function (letter) {
return letter.toUpperCase();
}))
});
언급URL : https://stackoverflow.com/questions/5122402/uppercase-first-letter-of-variable
'sourcecode' 카테고리의 다른 글
MySQL 오류 #1071 - 지정한 키가 너무 깁니다. 최대 키 길이는 767바이트입니다. (0) | 2023.10.31 |
---|---|
PowerShell에서 Write-Debug 출력을 콘솔에 표시하려면 어떻게 해야 합니까? (0) | 2023.10.31 |
심포니 CSRF and Ajax (0) | 2023.10.31 |
how to toggle attr() in jquery (0) | 2023.10.31 |
콘솔에서 프로그램이 실행되는지 확인하는 방법은 무엇입니까? (0) | 2023.10.26 |