JS字符串函数扩展

 1 /****************************************************
2 *CreateBy:joe zhou
3 *CreateDate:2011-9-4
4 *Description:字符串辅助函数
5 ****************************************************/
6 //String.prototype = {
7 // caption: function () {
8
9 // },
10 // leftPad: function (padChar, width) {
11 // if (this.length >= width) {
12 // return this;
13 // }
14 // }
15 //};
16
17 String.prototype.padLeft = function (padChar, width) {
18 var ret = this;
19 while (ret.length < width) {
20 if (ret.length + padChar.length < width) {
21 ret = padChar + ret;
22 }
23 else {
24 ret = padChar.substring(0, width-ret.length) + ret;
25 }
26 }
27 return ret;
28 };
29
30 String.prototype.padRight = function (padChar, width) {
31 var ret = this;
32 while (ret.length < width) {
33 if (ret.length + padChar.length < width) {
34 ret += padChar;
35 }
36 else {
37 ret += padChar.substring(0, width - ret.length);
38 }
39 }
40 return ret;
41 };
42
43 String.prototype.trim = function () {
44 return this.replace(/^\s+/, '').replace(/\s+$/, '');
45 };
46
47 String.prototype.trimLeft = function () {
48 return this.replace(/^\s+/, '');
49 };
50
51 String.prototype.trimRight = function () {
52 return this.replace(/\s+$/, '');
53 };
54
55 String.prototype.caption = function () {
56 if (this) {
57 return this.charAt(0).toUpperCase() + this.substr(1);
58 }
59 return this;
60 };
61
62 String.prototype.reverse = function () {
63 var ret = '';
64 for (var i = this.length - 1; i >= 0; i--) {
65 ret += this.charAt(i);
66 }
67 return ret;
68 };
69
70 String.prototype.startWith = function (compareValue, ignoreCase) {
71 if (ignoreCase) {
72 return this.toLowerCase().indexOf(compareValue.toLowerCase()) == 0;
73 }
74 return this.indexOf(compareValue) == 0
75 };
76
77 String.prototype.endWith = function (compareValue, ignoreCase) {
78 if (ignoreCase) {
79 return this.toLowerCase().lastIndexOf(compareValue.toLowerCase()) == this.length - compareValue.length;
80 }
81 return this.lastIndexOf(compareValue) == this.length - compareValue.length;
82 };

你可能感兴趣的:(字符串函数)