特殊字符的正则表达式

Regex for special ucwords

本文关键字:正则表达式 特殊字符      更新时间:2023-09-26

我想在JavaScript中做一个ucwords()形式的字符串:test1_test2_test3,它应该返回test1_test2_test3。

我已经在SO上找到了ucwords函数,但它只需要空格作为新的单词分隔符。下面是函数:

function ucwords(str) {
return (str + '').replace(/^([a-z])|'s+([a-z])/g, function ($1) {
    return $1.toUpperCase();
});

有人能帮忙吗?

只需在可接受的换行符列表中添加下划线:

function ucwords(str) {
return (str + '').replace(/^([a-z])|['s_]+([a-z])/g, function ($1) {
    return $1.toUpperCase();
})
};

您可以看到,我将's+替换为['s_]+

实例:http://jsfiddle.net/Bs8ZG/

尝试正则表达式

/(?:'b|_)([a-z])/

例如

另外两个看起来很完整的解决方案:

String.prototype.ucwords = function() {
    str = this.toLowerCase();
    return str.replace(/(^([a-zA-Z'p{M}]))|([ -][a-zA-Z'p{M}])/g,
        function($1){
            return $1.toUpperCase();
        });
}
$('#someDIV').ucwords();

来源:http://blog.justin.kelly.org.au/ucwords-javascript/

function ucwords (str) {
  return (str + '').replace(/^([a-z'u00E0-'u00FC])|'s+([a-z'u00E0-'u00FC])/g, function ($1) {
    return $1.toUpperCase();
  });
}
ucwords('kevin van  zonneveld');

来源:http://phpjs.org/functions/ucwords/

对我来说很好!