문제

I have this script which capitalizes the first letter of each sentence:

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

I want to add an exception: the first word of the sentence after ., ?, and ! characters should not be capitalized if the character is preceded by an xy word.

In my case from capitalization of string xy. is not correct. will be Capitalization of string xy. Is not correct.

I want as a result: Capitalization of string xy. is not correct.

Any ideas?

도움이 되었습니까?

해결책

Since Javascript doesn't support lookbehinds, you'll have a much easier time going through exactly the function you've written and then arbitrarily correcting the mistakenly capitalized bits back to lowercase.

Working example:

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

You probably could enhance it to handle an array of exceptions, or even use a regular expression.

Here's a working example: http://jsfiddle.net/remus/4EZBb/

다른 팁

You could use this:

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

Usage:

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

You could also solve this by making your .+? expression greedily consume the xy word, but that would get much more complicated.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top