JavaScript 扩展 String 属性,实现 endsWith、startsWith、trim、trimEnd、trimStart和toBytes。
//左匹配
String.prototype.endsWith = function (suffix) {
return (this.substr(this.length - suffix.length) === suffix);
}
//右匹配
String.prototype.startsWith = function (prefix) {
return (this.substr(0, prefix.length) === prefix);
}
//去前后空格
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
}
//去结尾空格
String.prototype.trimEnd = function () {
return this.replace(/\s+$/, '');
}
//去前面空格
String.prototype.trimStart = function () {
return this.replace(/^\s+/, '');
}
//转byte数组
String.prototype.toBytes = function () {
var ch, st, re = [];
for (var i = 0; i < this.length; i++) {
ch = this.charCodeAt(i); // get char
st = []; // set up "stack"
do {
st.push(ch & 0xFF); // push byte to stack
ch = ch >> 8; // shift value down by 1 byte
}
while (ch);
// add stack contents to result
// done because chars have "wrong" endianness
re = re.concat(st.reverse());
}
// return an array of bytes
return re;
}