Encodes the string into utf. - Node.js String

Node.js examples for String:Unicode

Description

Encodes the string into utf.

Demo Code

// Hive Colony Framework
// Copyright (C) 2008-2015 Hive Solutions Lda.
///*from  w  ww  .  ja  v  a  2 s  . co m*/
// This file is part of Hive Colony Framework.
//
// Hive Colony Framework is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Hive Colony Framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Hive Colony Framework. If not, see <http://www.gnu.org/licenses/>.

// __author__    = Jo?o Magalh?es <joamag@hive.pt>
// __version__   = 1.0.0
// __revision__  = $LastChangedRevision$
// __date__      = $LastChangedDate$
// __copyright__ = Copyright (c) 2008-2015 Hive Solutions Lda.
// __license__   = GNU General Public License (GPL), Version 3


/**
 * Encodes the string into utf.
 *
 * @return {String} The encoded string.
 */
String.prototype.encodeUtf = function() {
    var string = this.replace(/\r\n/g, "\n");
    var utfString = "";

    for (var index = 0; index < string.length; index++) {
        var character = string.charCodeAt(index);

        if (character < 128) {
            utfString += String.fromCharCode(character);
        } else if ((character > 127) && (character < 2048)) {
            utfString += String.fromCharCode((character >> 6) | 192);
            utfString += String.fromCharCode((character & 63) | 128);
        } else {
            utfString += String.fromCharCode((character >> 12) | 224);
            utfString += String.fromCharCode(((character >> 6) & 63) | 128);
            utfString += String.fromCharCode((character & 63) | 128);
        }
    }

    return utfString;
}

Related Tutorials