Question

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?

Was it helpful?

Solution

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/

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top