development

모든 문자열을 낙타 케이스로 변환

big-blog 2020. 6. 24. 07:07
반응형

모든 문자열을 낙타 케이스로 변환


Javascript 정규식을 사용하여 문자열을 낙타 케이스로 변환하는 방법은 무엇입니까?

EquipmentClass name또는 Equipment className또는 equipment class name또는Equipment Class Name

모두가되어야한다 : equipmentClassName.


코드를 보면 두 번의 replace호출 만으로 코드를 얻을 수 있습니다 .

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index == 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, '');
}

camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"

편집 : 또는 한 번의 replace호출로에서 공백을 캡처합니다 RegExp.

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
    if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
    return index == 0 ? match.toLowerCase() : match.toUpperCase();
  });
}

누군가 lodash를 사용 하는 경우 _.camelCase()기능이 있습니다.

_.camelCase('Foo Bar');
// → 'fooBar'

_.camelCase('--foo-bar--');
// → 'fooBar'

_.camelCase('__FOO_BAR__');
// → 'fooBar'

방금이 작업을 마쳤습니다.

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

여러 개의 replace 문을 연결하지 않으려 고했습니다. 내 기능에 $ 1, $ 2, $ 3가있는 곳. 그러나 이러한 유형의 그룹화는 이해하기 어렵고 크로스 브라우저 문제에 대한 귀하의 언급은 결코 생각하지 못했습니다.


이 솔루션을 사용할 수 있습니다 :

function toCamelCase(str){
  return str.split(' ').map(function(word,index){
    // If it is the first word make sure to lowercase all the chars.
    if(index == 0){
      return word.toLowerCase();
    }
    // If it is not the first word only upper case the first char and lowercase the rest.
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join('');
}

Scott의 특정 사례에서 나는 다음과 같이 갈 것입니다 :

String.prototype.toCamelCase = function() {
    return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
        if (p2) return p2.toUpperCase();
        return p1.toLowerCase();        
    });
};

'EquipmentClass name'.toCamelCase()  // -> equipmentClassName
'Equipment className'.toCamelCase()  // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName

정규식은 대문자로 시작하면 첫 문자와 공백 다음에 오는 알파벳 문자 (예 : 지정된 문자열에서 2 또는 3 회)와 일치합니다.

정규식을 /^([A-Z])|[\s-_](\w)/g정식으로 만들면 하이픈과 밑줄 유형 이름이 나타납니다.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat

function toCamelCase(str) {
  // Lower cases the string
  return str.toLowerCase()
    // Replaces any - or _ characters with a space 
    .replace( /[-_]+/g, ' ')
    // Removes any non alphanumeric characters 
    .replace( /[^\w\s]/g, '')
    // Uppercases the first character in each group immediately following a space 
    // (delimited by spaces) 
    .replace( / (.)/g, function($1) { return $1.toUpperCase(); })
    // Removes spaces 
    .replace( / /g, '' );
}

camelCase문자열에 JavaScript 함수를 찾으려고했는데 특수 문자가 제거되도록하고 싶었습니다 (그리고 위의 답변 중 일부가 무엇인지 이해하는 데 어려움이있었습니다). 이것은 cc young의 답변을 바탕으로 추가 된 의견과 $ peci & l 문자를 제거합니다.


c amel C ase 를 얻으려면

ES5

var camalize = function camalize(str) {
    return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
    {
        return chr.toUpperCase();
    });
}

ES6

var camalize = function camalize(str) {
    return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}


에 도착 C 아멜 S entence C ASE 또는 P의 ascal의 C의 ASE

var camelSentence = function camelSentence(str) {
    return  (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
    {
        return chr.toUpperCase();
    });
}

참고 :
악센트가있는 언어의 경우. 다음 À-ÖØ-öø-ÿ과 같이 정규식에 포함 하십시오
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g


regexp가 필요하지 않은 경우 Twinkle을 위해 오래 전에 만든 다음 코드를 살펴볼 수 있습니다 .

String.prototype.toUpperCaseFirstChar = function() {
    return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}

String.prototype.toLowerCaseFirstChar = function() {
    return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}

String.prototype.toUpperCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}

String.prototype.toLowerCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}

성능 테스트를 수행하지 않았으며 regexp 버전이 더 빠를 수도 있고 그렇지 않을 수도 있습니다.


ES6 접근 방식 :

const camelCase = str => {
  let string = str.toLowerCase().replace(/[^A-Za-z0-9]/g, ' ').split(' ')
                  .reduce((result, word) => result + capitalize(word.toLowerCase()))
  return string.charAt(0).toLowerCase() + string.slice(1)
}

const capitalize = str => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1)

let baz = 'foo bar'
let camel = camelCase(baz)
console.log(camel)  // "fooBar"
camelCase('foo bar')  // "fooBar"
camelCase('FOO BAR')  // "fooBar"
camelCase('x nN foo bar')  // "xNnFooBar"
camelCase('!--foo-¿?-bar--121-**%')  // "fooBar121"

lodash 는 트릭을 확실하고 잘 할 수 있습니다.

var _ = require('lodash');
var result = _.camelCase('toto-ce héros') 
// result now contains "totoCeHeros"

lodash"큰"라이브러리 (~ 4kB) 일 수도 있지만 일반적으로 스 니펫을 사용하거나 직접 빌드하는 많은 기능이 포함되어 있습니다.


다음은 작업을 수행하는 한 라이너입니다.

const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));

RegExp에 제공된 문자 목록을 기반으로 소문자 문자열을 분할하고 [.\-_\s]([]! 안에 추가) 단어 배열을 반환합니다. 그런 다음 문자열 배열을 첫 글자가 대문자 인 하나의 연결된 단어 문자열로 줄입니다. Reduce에는 초기 값이 없으므로 두 번째 단어부터 시작하여 첫 글자를 대문자로 시작합니다.

PascalCase를 원한다면 ,'')reduce 메소드에 초기 빈 문자열 추가하십시오 .


return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
    return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld

@Scott의 읽기 가능한 접근 방식에 따라 약간의 미세 조정

// 모든 문자열을 camelCase로 변환
var toCamelCase = 함수 (str) {
  str.toLowerCase () 반환
    .replace (/ [ ' "] / g,' ')
    .replace (/ \ W + / g, '')
    .replace (/ (.) / g, function ($ 1) {return $ 1.toUpperCase ();})
    .replace (/ / g, '');
}

아래 14 개의 순열은 모두 "equipmentClassName"의 결과와 동일합니다.

String.prototype.toCamelCase = function() {
  return this.replace(/[^a-z ]/ig, '')  // Replace everything but letters and spaces.
    .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, // Find non-words, uppercase letters, leading-word letters, and multiple spaces.
      function(match, index) {
        return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
      });
}

String.toCamelCase = function(str) {
  return str.toCamelCase();
}

var testCases = [
  "equipment class name",
  "equipment class Name",
  "equipment Class name",
  "equipment Class Name",
  "Equipment class name",
  "Equipment class Name",
  "Equipment Class name",
  "Equipment Class Name",
  "equipment className",
  "equipment ClassName",
  "Equipment ClassName",
  "equipmentClass name",
  "equipmentClass Name",
  "EquipmentClass Name"
];

for (var i = 0; i < testCases.length; i++) {
  console.log(testCases[i].toCamelCase());
};


이 솔루션을 사용할 수 있습니다 :

String.prototype.toCamelCase = function(){
  return this.replace(/\s(\w)/ig, function(all, letter){return letter.toUpperCase();})
             .replace(/(^\w)/, function($1){return $1.toLowerCase()});
};

console.log('Equipment className'.toCamelCase());


약간 수정 된 Scott의 답변 :

toCamelCase = (string) ->
  string
    .replace /[\s|_|-](.)/g, ($1) -> $1.toUpperCase()
    .replace /[\s|_|-]/g, ''
    .replace /^(.)/, ($1) -> $1.toLowerCase()

이제 '-'와 '_'도 바꿉니다.


내 해결책이 있습니다.

const toCamelWord = (word, idx) =>
  idx === 0 ?
  word.toLowerCase() :
  word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();

const toCamelCase = text =>
  text
  .split(/[_-\s]+/)
  .map(toCamelWord)
  .join("");

console.log(toCamelCase('User ID'))


이 방법은 여기에서 대부분의 답변보다 성능이 뛰어나지 만 약간의 해킹이지만 대체는 없으며 정규 표현식도 없으며 단순히 camelCase 인 새 문자열을 작성합니다.

String.prototype.camelCase = function(){
    var newString = '';
    var lastEditedIndex;
    for (var i = 0; i < this.length; i++){
        if(this[i] == ' ' || this[i] == '-' || this[i] == '_'){
            newString += this[i+1].toUpperCase();
            lastEditedIndex = i+1;
        }
        else if(lastEditedIndex !== i) newString += this[i].toLowerCase();
    }
    return newString;
}

이것은 밑줄을 포함하여 영문자 이외의 문자를 제거하여 CMS의 답변을 바탕으로합니다 \w.

function toLowerCamelCase(str) {
    return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
        if (+match === 0 || match === '-' || match === '.' ) {
            return ""; // or if (/\s+/.test(match)) for white spaces
        }
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e

정규식을 사용하지 않고 소문자 낙타 대소 문자 ( "TestString")에서 소문자 낙타 대소 문자 ( "testString") (대면 정규식은 악의입니다) :

'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), '');

나는 약간 더 공격적인 솔루션을 만들었습니다.

function toCamelCase(str) {
  const [first, ...acc] = str.replace(/[^\w\d]/g, ' ').split(/\s+/);
  return first.toLowerCase() + acc.map(x => x.charAt(0).toUpperCase() 
    + x.slice(1).toLowerCase()).join('');
}

위의 방법은 대문자가 아닌 알파벳이 아닌 모든 문자와 단어의 소문자 부분을 제거합니다.

  • Size (comparative) => sizeComparative
  • GDP (official exchange rate) => gdpOfficialExchangeRate
  • hello => hello

function convertStringToCamelCase(str){
    return str.split(' ').map(function(item, index){
        return index !== 0 
            ? item.charAt(0).toUpperCase() + item.substr(1) 
            : item.charAt(0).toLowerCase() + item.substr(1);
    }).join('');
}      

이 질문에는 또 다른 대답이 필요했기 때문에 ...

이전 솔루션 중 여러 가지를 시도했지만 모두 하나의 결함이있었습니다. 일부는 구두점을 제거하지 않았습니다. 일부는 숫자가있는 경우를 처리하지 않았습니다. 일부는 여러 문장 부호를 연속으로 처리하지 않았습니다.

그들 중 누구도와 같은 문자열을 처리하지 않았습니다 a1 2b. 이 경우에 명시 적으로 정의 된 규칙은 없지만 다른 스택 오버플로 질문 은 숫자를 밑줄로 구분하는 것이 좋습니다.

이것이 가장 성능이 좋은 대답 (3 개의 정규 표현식이 하나 또는 두 개가 아닌 문자열을 통과한다는 것)은 의심 스럽지만 생각할 수있는 모든 테스트를 통과합니다. 그러나 솔직히 말해서 성능이 중요한 낙타 사례 변환을 많이 수행하는 경우를 상상할 수 없습니다.

( 이것은 npm 패키지 로 추가되었습니다 . Camel Case 대신 Pascal Case를 반환하는 선택적 boolean 매개 변수도 포함되어 있습니다.)

const underscoreRegex = /(?:[^\w\s]|_)+/g,
    sandwichNumberRegex = /(\d)\s+(?=\d)/g,
    camelCaseRegex = /(?:^\s*\w|\b\w|\W+)/g;

String.prototype.toCamelCase = function() {
    if (/^\s*_[\s_]*$/g.test(this)) {
        return '_';
    }

    return this.replace(underscoreRegex, ' ')
        .replace(sandwichNumberRegex, '$1_')
        .replace(camelCaseRegex, function(match, index) {
            if (/^\W+$/.test(match)) {
                return '';
            }

            return index == 0 ? match.trimLeft().toLowerCase() : match.toUpperCase();
        });
}

테스트 사례 (Jest)

test('Basic strings', () => {
    expect(''.toCamelCase()).toBe('');
    expect('A B C'.toCamelCase()).toBe('aBC');
    expect('aB c'.toCamelCase()).toBe('aBC');
    expect('abc      def'.toCamelCase()).toBe('abcDef');
    expect('abc__ _ _def'.toCamelCase()).toBe('abcDef');
    expect('abc__ _ d_ e _ _fg'.toCamelCase()).toBe('abcDEFg');
});

test('Basic strings with punctuation', () => {
    expect(`a'b--d -- f.h`.toCamelCase()).toBe('aBDFH');
    expect(`...a...def`.toCamelCase()).toBe('aDef');
});

test('Strings with numbers', () => {
    expect('12 3 4 5'.toCamelCase()).toBe('12_3_4_5');
    expect('12 3 abc'.toCamelCase()).toBe('12_3Abc');
    expect('ab2c'.toCamelCase()).toBe('ab2c');
    expect('1abc'.toCamelCase()).toBe('1abc');
    expect('1Abc'.toCamelCase()).toBe('1Abc');
    expect('abc 2def'.toCamelCase()).toBe('abc2def');
    expect('abc-2def'.toCamelCase()).toBe('abc2def');
    expect('abc_2def'.toCamelCase()).toBe('abc2def');
    expect('abc1_2def'.toCamelCase()).toBe('abc1_2def');
    expect('abc1 2def'.toCamelCase()).toBe('abc1_2def');
    expect('abc1 2   3def'.toCamelCase()).toBe('abc1_2_3def');
});

test('Oddball cases', () => {
    expect('_'.toCamelCase()).toBe('_');
    expect('__'.toCamelCase()).toBe('_');
    expect('_ _'.toCamelCase()).toBe('_');
    expect('\t_ _\n'.toCamelCase()).toBe('_');
    expect('_a_'.toCamelCase()).toBe('a');
    expect('\''.toCamelCase()).toBe('');
    expect(`\tab\tcd`.toCamelCase()).toBe('abCd');
    expect(`
ab\tcd\r

-_

|'ef`.toCamelCase()).toBe(`abCdEf`);
});

내 제안은 다음과 같습니다.

function toCamelCase(string) {
  return `${string}`
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
}

또는

String.prototype.toCamelCase = function() {
  return this
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
};

테스트 사례 :

describe('String to camel case', function() {
  it('should return a camel cased string', function() {
    chai.assert.equal(toCamelCase('foo bar'), 'fooBar');
    chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar');
    chai.assert.equal(toCamelCase('fooBar'), 'fooBar');
    chai.assert.equal(toCamelCase('FooBar'), 'fooBar');
    chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar');
    chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar');
    chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121');
  });
});

나는 이것이 오래된 대답이라는 것을 알고 있지만 공백과 _ (lodash)를 모두 처리합니다.

function toCamelCase(s){
    return s
          .replace(/_/g, " ")
          .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
          .replace(/\s/g, '')
          .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

console.log(toCamelCase("Hello world");
console.log(toCamelCase("Hello_world");

// Both print "helloWorld"

기본 접근 방식은 문자열을 대문자 또는 공백과 일치하는 정규 표현식으로 분할하는 것입니다. 그런 다음 조각을 다시 붙입니다. 트릭은 브라우저에서 정규식 분할이 깨지거나 이상한 다양한 방법을 다룰 것입니다. 그 문제를 해결하기 위해 누군가가 쓴 라이브러리 나 무언가가 있습니다. 내가 찾아 볼게

여기 링크가 있습니다 : http://blog.stevenlevithan.com/archives/cross-browser-split


편집 : 이제 변경없이 IE8에서 작동합니다.

편집 : 나는 camelCase가 실제로 무엇인지에 대해 소수였습니다 (Leading character 소문자 대 대문자). 커뮤니티는 대체로 주요한 소문자가 낙타의 경우이고 주요 자본은 파스칼의 경우라고 믿고 있습니다. 정규식 패턴 만 사용하는 두 가지 함수를 만들었습니다. :) 그래서 우리는 통일 된 어휘를 사용합니다. 나는 대다수와 일치하도록 입장을 바꿨습니다.


두 가지 경우 모두 단일 정규식이라고 생각합니다.

var camel = " THIS is camel case "
camel = $.trim(camel)
    .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
    .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
    .replace(/(\s.)/g, function(a, l) { return l.toUpperCase(); })
    .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "thisIsCamelCase"

또는

var pascal = " this IS pascal case "
pascal = $.trim(pascal)
  .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
  .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
  .replace(/(^.|\s.)/g, function(a, l) { return l.toUpperCase(); })
  .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "ThisIsPascalCase"

함수에서 :이 함수에서 대체가 공백이 아닌 빈 문자열로 az가 아닌 것을 바꾸고 있음을 알 수 있습니다. 이것은 대문자로 단어 경계를 만드는 것입니다. "hello-MY # world"-> "HelloMyWorld"

// remove \u00C0-\u00ff] if you do not want the extended letters like é
function toCamelCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

function toPascalCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

노트:

  • 가독성을 위해 패턴 (/ [^ AZ] / ig)에 대소 문자 구분 플래그 (i)추가하는 대신 A-Za-z를 그대로 두었습니다 .
  • 이것은 IE8 (더 이상 IE8을 사용하는 사람) 에서 작동합니다 . IE11, IE10, IE9, IE8, IE7 및 IE5에서 테스트 한 (F12) dev 도구 사용. 모든 문서 모드에서 작동합니다.
  • 이것은 공백으로 시작하거나 공백없이 시작하는 첫 번째 문자열을 올바르게 입력합니다.

즐겨


나는 이것이 효과가 있다고 생각한다 ..

function cammelCase(str){
    let arr = str.split(' ');
    let words = arr.filter(v=>v!='');
    words.forEach((w, i)=>{
        words[i] = w.replace(/\w\S*/g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1);
        });
    });
    return words.join('');
}

String.prototypes는 읽기 전용이므로 String.prototype.toCamelCase ()를 사용하지 마십시오. 대부분의 js 컴파일러는이 경고를 표시합니다.

나처럼 문자열에 항상 하나의 공간 만 포함한다는 것을 아는 사람들은 더 간단한 접근법을 사용할 수 있습니다.

let name = 'test string';

let pieces = name.split(' ');

pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));

return pieces.join('');

좋은 하루 되세요. :)


turboCommons 라이브러리를 사용하는 매우 쉬운 방법 :

npm install turbocommons-es5

<script src="turbocommons-es5/turbocommons-es5.js"></script>

<script>
    var StringUtils = org_turbocommons.StringUtils;
    console.log(StringUtils.formatCase('EquipmentClass', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('Equipment className', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('equipment class name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('Equipment Class Name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
</script>

StringUtils.FORMAT_CAMEL_CASE 및 StringUtils.FORMAT_UPPER_CAMEL_CASE를 사용하여 첫 번째 대소 문자 변형을 생성 할 수도 있습니다.

여기에 더 많은 정보가 있습니다 :

문자열을 CamelCase, UpperCamelCase 또는 lowerCamelCase로 변환

참고 URL : https://stackoverflow.com/questions/2970525/converting-any-string-into-camel-case

반응형