代码-JS之扩展String对象

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<script>

    //扩展内置对象String,添加ucfirst方法。
    String.prototype.ucfirst = function(){
        //console.log(this); // this 表示 String的一个实例对象,其实就是要操作的字符串
        return this.substr(0,1).toUpperCase() + this.substr(1).toLowerCase();
    };

    //扩展内置对象String,添加myTrim方法。
    String.prototype.myTrim = function () {
        return this.replace(/\s/g, '');
    };

        var s1 = new String('hello');
        console.log(s1.ucfirst());  //结果:Hello

        var s2 = new String('            hello   ');
        console.log(s2.myTrim());   //结果:hello
</script>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39723600/article/details/83239600