2014-01-12 3 views
0

I가 각 문장의 첫 글자를 대문자로이 스크립트 :문장 총액 예외

String.prototype.capitalize = function() { 
    return this.replace(/.+?[\.\?\!](\s|$)/g, function (txt) { 
     return txt.charAt(0).toUpperCase() + txt.slice(1); 
    }); 
}; 

내가 예외를 추가 할 : . 후 문장의 첫 단어, ?, 그리고 ! 문자가 안 문자 앞에 xy 단어가 대문자로 표기됩니다. Capitalization of string xy. is not correct.

어떤 아이디어 : capitalization of string xy. is not correct.에서 내 경우

나는 결과로 원하는 Capitalization of string xy. Is not correct.

될 것인가?

+0

정규식으로이 문제를 해결하려고하지 마십시오. JS는 lookbehind를 지원하지 않습니다. – Bergi

+0

@Bergi'xy '뒤에 단어를 소문자로 표시 할 수 있습니까? – zsola3075457

+0

물론 가능하지만 대체 정규식을 적용해서는 안됩니다. – Bergi

답변

2

JavaScript는 lookbehinds를 지원하지 않으므로 작성한 함수를 정확하게 통과 한 다음 실수로 대문자로 된 비트를 소문자로 임의로 수정하는 것이 훨씬 쉽습니다.

근무 예 :

String.prototype.capitalize = function(exception) { 
    var result = this.replace(/.+?[\.\?\!](\s|$)/g, function (txt) { 
     return txt.charAt(0).toUpperCase() + txt.slice(1); 
    }); 
    var r = new RegExp(exception + "\\.\\s*\(\\w+\)", "i"); 
    return result.replace(r, function(re) { return(re.toLowerCase()) }); 
}; 

alert("capitalization of string xy. is not correct.".capitalize("xy")); 

당신은 아마 예외의 배열을 처리, 심지어 정규 표현식을 사용하도록 향상시킬 수 있습니다. 여기

는 작업 예제 :

String.prototype.capitalizeSentencesWithout = function(word) { 
    return this.replace(/.+?[\.\?\!](?:\s|$)/g, function (txt, pos, orig) { 
     if (orig.slice(pos-word.length-2, pos-2) == word) 
      return txt; 
     return txt.charAt(0).toUpperCase() + txt.slice(1); 
    }); 
}; 

사용법 :

> "capitalization of string xy. is correct.".capitalizeSentencesWithout("xy") 
"Capitalization of string xy. is correct." 

또한 욕심 xy 단어를 소비하여 .+? 표현함으로써이 문제를 해결할 수 http://jsfiddle.net/remus/4EZBb/

+0

...하지만 소문자 인 다음 경기가 필요합니다! – Bergi

+0

그래, 그것에서 작업하는 – brandonscript

+0

확인을 :) 업데이트 작업 예를 참조하십시오. – brandonscript

1

이 사용할 수 그러나 그것은 훨씬 더 복잡해질 것이다.