[js高手之路] 跟GhostWu一起封装一个字符串工具库-扩展trim,trimLeft,trimRight方法(2)...

本文介绍了一个自定义的字符串处理工具库实现,该工具库提供了三种去除字符串前后空格的方法:trimLeft、trimRight 和 trim,并通过 JavaScript 实现了这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们接着上一篇的继续,在上一篇我们完成了工具库的架构,本文扩展字符串去空格的方法, 一共有3个

1,trimLeft: 去除字符串左边的空格

2,trimRight: 去除字符串右边的空格

3,trim: 去除字符串两边的空格

 1 ; (function (window, undefined) {
 2     function init(obj, s) {
 3         if (s !== null && s !== undefined) {
 4             if (typeof s === 'string') {
 5                 obj.s = s;
 6             } else {
 7                 obj.s = s.toString();
 8             }
 9         } else {
10             obj.s = s;
11         }
12     }
13 
14     function G(s) {
15         init(this, s);
16     }
17 
18     function GhostWu(s) {
19         return new G(s);
20     }
21 
22     var sProto = String.prototype;
23     G.prototype = {
24         constructor: G,
25         capitalize: function () {
26             return new this.constructor(this.s.slice(0, 1).toUpperCase() + this.s.substring(1).toLowerCase());
27         },
28         trimLeft : function () {
29             var s;
30             if (sProto.trimLeft === 'undefined')
31                 s = this.s.trimLeft();
32             else
33                 s = this.s.replace(/^\s+/g, '');
34             return new this.constructor(s);
35         },
36         trimRight : function () {
37             var s;
38             if (sProto.trimRight === 'undefined')
39                 s = this.s.trimRight();
40             else
41                 s = this.s.replace(/\s+$/g, '');
42             return new this.constructor(s);
43         },
44         trim : function () {
45             var s;
46             if (typeof sProto.trim === 'undefined') {
47                 s = this.s.replace(/^\s+|\s+$/g, '');
48             } else {
49                 s = this.s.trim();
50             }
51             return new this.constructor(s);
52         }
53     };
54 
55     window.G = GhostWu;
56 })(window, undefined);
alert( '(' + G( ' ghostwu ' ).s + ')' );
alert( '(' + G( ' ghostwu ' ).trim().s + ')' );
alert( '(' + G( ' ghostwu ' ).trimLeft().trimRight().s + ')' );

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值