Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String 的扩展和 stringBuilder 也是很有意思的 #9

Open
lzpong opened this issue Aug 22, 2017 · 0 comments
Open

String 的扩展和 stringBuilder 也是很有意思的 #9

lzpong opened this issue Aug 22, 2017 · 0 comments

Comments

@lzpong
Copy link
Owner

lzpong commented Aug 22, 2017

/*string 的扩展*/
String.prototype.toInt=function(){return parseInt(this);}
String.prototype.toFloat=function(){return parseFloat(this);}
String.prototype.trim = function (s) {
  if (s) return this.trimEnd(s) .trimStart(s);
  return this.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '');
}
String.prototype.trimEnd = function (s) {
  if (this.endsWith(s))
    return this.substring(0, this.length - s.length);
  return this;
}
String.prototype.trimStart = function (s) {
  if (this.startsWith(s))
    return this.slice(s.length);
  return this;
}
String.prototype.startsWith = function (str) {
  return (this.indexOf(str) == 0);
}
String.prototype.endsWith = function (str) {
  return (str.length <= this.length && this.substr(this.length - str.length, str.length) == str);
}
String.prototype.remove = function (start, length) {
  var str1 = this.substring(0, start);
  var str2 = this.substring(start + length, this.length);
  return str1 + str2;
}
String.prototype.insert = function (index, str) {
  var str1 = this.substring(0, index);
  var str2 = this.substring(index, this.length);
  return str1 + str + str2;
}
String.prototype.hashCode = function () {
  var h = 31;
  var i = 0;
  var l = this.length;
  while (i < l) h ^= (h << 5) + (h >> 2) + this.charCodeAt(i++);
  return h;
}
String.format = function (fmt) {
  for (var i = 1; i < arguments.length; i++) {
    var reg = new RegExp('\\{' + (i - 1) + '\\}', 'ig');
    fmt = fmt.replace(reg, arguments[i]);
  }
  return fmt;
}

var stringBuilder = function (str) {
  this.arr = new Array();
  this.length = 0;
  if (str) {
    this.arr.push(str);
    this.length += str.length;
  }
  if (!stringBuilder.created) {
    stringBuilder.prototype.append = function (str) {
      this.arr.push(str);
      this.length += str.length;
      return this;
    };
    stringBuilder.prototype.clear = function () {
      this.arr.splice(0, this.arr.length);
      this.length = 0;
      return this;
    };
    stringBuilder.prototype.join = function (str) {
      return this.arr.join(str);
    };
    stringBuilder.created = true;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant