[js高手之路] 跟GhostWu一起封装一个字符串工具库-扩展trim,trimLeft,trimRight方法(2)
2023-09-11 14:19:51 时间
我们接着上一篇的继续,在上一篇我们完成了工具库的架构,本文扩展字符串去空格的方法, 一共有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 + ')' );
相关文章
- h5 录音 自动生成proto Js语句 UglifyJS-- 对你的js做了什么 【原码笔记】-- protobuf.js 与 Long.js 【微信开发】-- 发送模板消息 能编程与会编程 vue2入坑随记(二) -- 自定义动态组件 微信上传图片
- 【Javascript】通过Js来修改css中ClassName名称(完整代码)
- js 实现自定转驼峰格式
- Vue - 在纯 JS 文件中调用自定义组件 / 类似 ElementUI 弹框组件 Message、Modal(在纯 js 文件中通过 import 方式引入并调用弹框模态框组件显示出来,)
- JS功能封装 - 小数四则运算精度丢失缺陷
- JS Leetcode 220. 存在重复元素 III 题解分析,暴力解法与桶排序
- 使用 js 修饰器封装 axios
- 【HarmonyOS】【JS】 鸿蒙js开发使用div自带的scroll,滑动条拉不到最下面?
- download.js (实例2)下载
- el-dialog 或dialog 封装 通过js控制
- JS模式:jq中简单的模式--》采摘自js设计(tomxu_version)
- js用replaceAll全部替换的方法
- JS内置对象之Math(附代码及演示效果)
- JS模板引擎handlebars.js的简单使用
- [js高手之路] 跟GhostWu一起封装一个字符串工具库-扩展camelize与dasherize方法(3)
- 【Laya + TS + JS】SheetJS(js-xlsx)前端生成Excel表格
- js css 实现简单的计算器
- JavaScript经典实例之分页(简单易用)原生js封装分页(一次性数据)
- 自己根据js的兼容封装了一个小小的js库
- JQuery/JS插件 json2.js
- js 数组,根据数组内部的对象中的某个属性值进行分组
- dom工具库codingWeb.js,封装与总结
- 封装异步API-js先执行完一个函数后再执行下面的逻辑或者方法