Escapes/Unescapes a string in such a way that most whitespace is visible - Node.js String

Node.js examples for String:Escape

Description

Escapes/Unescapes a string in such a way that most whitespace is visible

Demo Code

/**/*from  w ww  .j a  va2  s  .  co  m*/
 * Escapes a string in such a way that most whitespace is visible
 *
 * @param val
 * @returns {string|Pomo.Parser.Object}
 */
var escapeString = function (val) {
    var return_value;
    if (val.constructor != String()) {
        return_value = val;
    }
    if (val.replace) {
        return_value = val
            .replace(/[\"]/g, '\\"')
            .replace(/[\\]/g, '\\')
            .replace(/[\/]/g, '\/')
            .replace(/[\b]/g, '\\b')
            .replace(/[\f]/g, '\\f')
            .replace(/[\n]/g, '\\n')
            .replace(/[\r]/g, '\\r')
            .replace(/[\t]/g, '\\t');
    }

    return return_value;
};

/**
 * Unescapes a string like the output of escapeString()
 *
 * @param val
 * @returns string
 */
var unescapeString = function (val) {
    var return_value;
    if (!!val && !!val.replace) {
        return_value = val
            .replace("\\n", '\n')
            .replace("\\r", '\r')
            .replace("\\t", '\t')
            .replace("\\f", '\f')
            .replace("\\b", '\b')
            .replace("\\r", '\r');
    }

    return return_value;
};

Related Tutorials