2016-10-18 2 views
1

나는 문장을 대문자로 쓰는 기능이있다.자바 스크립트에서 이름을 대문자로 바꾸기

D'Agostino, Fred 
D'Agostino, Ralph B. 
D'Allonnes, C. Revault 
D'Amanda, Christopher 

기능 :

getCapitalized(str){ 
    var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; 
    return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) { 
     if (index > 0 && index + match.length !== title.length && 
     match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && 
     (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') && 
     (title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") && 
     title.charAt(index - 1).search(/[^\s-]/) < 0) { 
     return match.toLowerCase(); 
     } 
     if (match.substr(1).search(/[A-Z]|\../) > -1) { 
     return match; 
     } 
     return match.charAt(0).toUpperCase() + match.substr(1); 
    }); 
    } 

이 사람이 나에게 문제를 파악하는 데 도움 수를하지만 그 수 없습니다 내가 기대하고,

D'agostino, Fred 
D'agostino, Ralph B. 
D'allonnes, C. Revault 
D'amanda, Christopher 

를 같은 이름을 대문자로? (title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'")을 사용해 보았지만 도움이되지 않습니다.

+0

'''를 테스트하는 코드 부분이 현재 'smallWords'와 일치하는 것에 만 적용되지 않습니까? – nnnnnn

+0

오, 이제 알겠습니다! 감사합니다 @ nnnnnn –

+0

@nnnnnn 이것에 대한 최적의 솔루션이 있습니까? –

답변

3

은 당신이 알아서하는 데 필요한 모든 사용 사례에 대해 잘 모르겠지만, 당신이 묻는 질문에 대해, 당신은 단어 경계를 찾습니다 정규식 사용할 수 있습니다

function capitalizeName(name) { 
 
    return name.replace(/\b(\w)/g, s => s.toUpperCase()); 
 
} 
 

 
console.log(capitalizeName(`D'agostino, Fred`)); 
 
console.log(capitalizeName(`D'agostino, Ralph B.`)); 
 
console.log(capitalizeName(`D'allonnes, C. Revault`)); 
 
console.log(capitalizeName(`D'amanda, Christopher`));

관련 문제