Small tips: JS / CSS to achieve a string of words capitalized

css implementation:

text-transform:capitalize;

A JS code:

String.prototype.firstUpperCase = function(){
        return this.replace(/\b(\w)(\w*)/g,function($0,$1,$2){
            return $1.toUpperCase() + $2.toLowerCase();
        })
}
var result = "i'm hello world".firstUpperCase();;
console.log(result); //I'M Hello World

Note: the regular expression \ b will abbreviation, such as I'm split into two portions, resulting in the output I'M, can not be used \ b

JS Code II:

String.prototype.firstUpperCase = function(){
    let arr = this.split(' ');
    let uppserCase = ([first,...rest]) => first.toUpperCase() + rest.join('');
    let result = '';
    arr.forEach((val) => {
        result += uppserCase(val) + ' ';
    })
    return result;
}
//结果://I'm Hello World 

JS code three:

String.prototype.firstUpperCase = function(){
    let arr = this.split(' ');
    let result = '';
    arr.forEach((val) => {
        result += val.charAt(0).toUpperCase() + val.slice(1) + ' ';
    })
    return result;
}
//结果://I'm Hello World 

JS code four:

String.prototype.firstUpperCase = function(){
    let arr = this.split(' ');
    let result = '';
    arr.forEach((val) => {
        result += `${val[0].toUpperCase()}${val.slice(1)} `;
    })
    return result;
}
//结果://I'm Hello World 

Note:
\b: match a word boundary, that is, it refers to the location and spaces between words. For example, 'erb' can match the "never" in the 'er', but does not match the "verb" in the 'er'.
\w: Match any word character including underscore. It is equivalent to the '[A-Za-z0-9_] '.
*: Matches the preceding subexpression zero or more times. For example, zo can match the "z" and "zoo". It is equivalent to {0}.
\s: Matches any whitespace characters, including spaces, tabs, page breaks, and so on. It is equivalent to [fnrtv].
\S: Matches any non-whitespace characters. Is equivalent to [^ \ f \ n \ r \ t \ v].

Reference address the problem: JavaScript string of words capitalized implementation

Guess you like

Origin www.cnblogs.com/moqiutao/p/11449101.html