Programing

변수의 첫 글자 대문자

lottogame 2020. 9. 22. 20:58
반응형

변수의 첫 글자 대문자


나는 웹을 통해 검색했지만 나를 도울 수있는 것을 찾을 수 없습니다. 변수 내에서 각 단어의 첫 글자를 대문자로 만들고 싶습니다.

지금까지 나는 시도했다 :

toUpperCase();

그리고 모든 문자를 대문자로 표시하므로 운이 없었습니다.


단어를 시작하는 소문자를 대문자로 바꾸 려면 .replace[MDN] 기능을 사용하십시오 .

var str = "hello world";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Hello World"


편집 : az 이외의 단어 문자를 다루는 경우 다음 (더 복잡한) 정규식이 용도에 더 적합 할 수 있습니다.

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

@Dementic이 나를 올바른 길로 인도 한 것에 대해 공로를 인정해야합니다. 여러분이 제안하는 것보다 훨씬 간단합니다.


http://phpjs.org/functions/ucwords:569 에 좋은 예가 있습니다.

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

(간결성을 위해 소스에서 함수 설명을 생략했습니다. 자세한 내용은 링크 된 소스를 참조하십시오)

편집 :이 기능은 (질문 제목이 묻는 것처럼) 문자열의 첫 글자가 아니라 각 단어의 첫 글자를 대문자로 표시합니다 (질문이 묻는대로)


순수한 자바 스크립트 솔루션을 추가하고 싶었습니다 (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'));


substring () 및 toUpperCase ()를 사용하여 첫 번째 문자를 꺼내고 대문자로 만든 다음 문자열의 첫 번째 문자를 결과로 바꿀 수 있다고 생각합니다.

myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"

나는 그것이 당신에게 효과가 있다고 생각합니다. 고려해야 할 또 다른 사항은이 데이터가 표시되는 경우 CSS 속성 "text-transform : capitalize"가있는 컨테이너에 클래스를 추가 할 수 있다는 것입니다.


이렇게하려면 사용하려는 경우 Javascript가 실제로 필요하지 않습니다.

$('#test').css('textTransform', '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));


[최신 정보:]

Thanks to @FelixKling for the tip:

$("#test").text(function(i, text) {
    return text.substr(0,1).toUpperCase() + text.substr(1);
});

Building on @peter-olson's answer, I took a more object oriented approach without 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"

Example: http://jsfiddle.net/LzaYH/1/


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

var mystring = "hello World"
mystring = mystring.substring(0,1).toUpperCase() + 
mystring.substring(1,mystring.length)

console.log(mystring) //gives you Hello World

Based completely on @Dementric 's answer, this solution is ready to call with a simple jQuery method, 'ucwords'... Thanks to everyone who contributed here!!!

$.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
}

});

EXAMPLE: This can be called using the method

var string = "this is a test";
string = $.ucwords(string); // Returns "This Is A Test"

You can use text-transform: capitalize; for this work -

HTML -

<input type="text" style="text-transform: capitalize;" />

JQuery -

$(document).ready(function (){
   var asdf = "WERTY UIOP";
   $('input').val(asdf.toLowerCase());
});

Try This

Note: It's only change visual representation of the string. If you alert this string it's always show original value of the string.


You can try this simple code with the features of ucwords in PHP.

function ucWords(text) {
    return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');

It will keep the Upper Cases unchanged.


The string to lower before Capitalizing the first letter.

(Both use Jquery syntax)

function CapitaliseFirstLetter(elementId) {
    var txt = $("#" + elementId).val().toLowerCase();
    $("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
    return $1.toUpperCase(); }));
    }

In addition a function to Capitalise the WHOLE string:

function CapitaliseAllText(elementId) {
     var txt = $("#" + elementId).val();
     $("#" + elementId).val(txt.toUpperCase());
     }

Syntax to use on a textbox's click event:

onClick="CapitaliseFirstLetter('TextId'); return false"

I have used this code -

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

Html:

<input class="capitalize" name="Address" type="text" value="" />

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

Without 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

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


Here is unicode-safe ucwords() function, which additionally respects double-lastnames like Russian Засс-Ранцев and some noble names like Honoré de Balzac, d'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd, etc:

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

참고URL : https://stackoverflow.com/questions/5122402/uppercase-first-letter-of-variable

반응형