我有这样一个脚本,它把每个句子的第一个字母大写起来:
String.prototype.capitalize = function() {
return this.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1);
});
};我想添加一个例外:如果该字符前面有一个.、?和!字符,则该句子的第一个单词不应该大写。
在我的例子中,capitalization of string xy. is not correct.将是Capitalization of string xy. Is not correct.
我希望结果是:Capitalization of string xy. is not correct.
有什么想法吗?
发布于 2014-01-12 21:55:57
因为Javascript不支持后置查找,所以您可以更容易地完成编写的函数,然后任意地将错误大写的位纠正回小写。
工作实例:
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"));您可能会对其进行增强,以处理一系列异常,甚至可以使用正则表达式。
下面是一个有用的示例:http://jsfiddle.net/remus/4EZBb/
发布于 2014-01-12 22:03:59
你可以用这个:
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单词来解决这个问题,但是这会变得更加复杂。
https://stackoverflow.com/questions/21080608
复制相似问题