String.prototype.slice(beginIndex, endIndex)
slice 方法是用来从父字符串中截取子字符串并返回一个新的字符串,接受两个参数。
实现:
String.prototype.slice1 = function(beginIndex, endIndex) {let len = this.length, str = '';endIndex = (typeof endIndex != 'undefined') ? endIndex : len;let start = beginIndex || 0;start = (start >= 0) ? start : Math.max(0, len + start);let end = (typeof endIndex == 'number') ? Math.min(endIndex, len) : len;if (endIndex < 0) {end = len + end;}while(start < end) {str += this[start];start++;}return str;}
String.prototype.substr(beginIndex, endIndex)
substr 返回一个字符串中从指定位置开始到指定字符串位置,截取初一个新的字符串。接受两个参数。
实现:
String.prototype.substr1 = function(start, length) {let len = this.length, str = '';length = (typeof length != 'undefined') ? length : len; let begin = start || 0;begin = (begin >= 0) ? begin : Math.max(0, start + len);while (length > 0) {if (!this[begin]) break;str += this[begin++];length--;}return str;}
String.prototype.substring(start, end)
substring 方法返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集。
String.prototype.substring1 = function(start, end) {let len = this.length, str = '';end = (typeof end == 'undefined') ? len - 1 : end;end = (typeof end == 'number') ? Math.min(end, len) : len;let beign = start || 0;begin = +beign;if (isNaN(beign) || beign < 0) beign = 0;let result = 0;if (end < begin) {result = end;end = begin;beign = result;}let size = end - begin; // 实际要截取的长度。if (size > 0) {if (this.charAt) {for (let i = 0; i < size; i++) {result += this.charAt(begin + i);}} else {for (let i = 0; i < size; i++) {result += this[begin + i];}}}return str;}