JavaScript 扩展 String 属性

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;
}
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花