开发者

Regex for special ucwords

I want to do an ucwords() in JavaScript on a string of the form: test1_test2_test开发者_C百科3 and it should return Test1_Test2_Test3.

I already found an ucwords function on SO, but it only takes space as new word delimiters. Here is the function:

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

Could anyone help?


Just add an underscore to the list of acceptable word breaks:

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

As you can see ive replace the bit which was \s+ to [\s_]+

Live example: http://jsfiddle.net/Bs8ZG/


Try the regular expression

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

For an example see here


Two other solutions that seems pretty complete:

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

Source: 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');

Source: http://phpjs.org/functions/ucwords/

Worked fine to me!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜