Swap and replace String - Node.js String

Node.js examples for String:Replace

Description

Swap and replace String

Demo Code

String.prototype.swap = function(target, replacement, limit) {
    limit = limit || Infinity;//from w w  w  .j a  v  a2 s. com
    var me = this, i = 0, tLen = target.length, rLen = replacement.length;
    while(limit-- && (i = me.indexOf(target, i)) + 1) {
        me = me.slice(0, i) + replacement + me.slice(i + tLen);
        i += rLen;
        if (!tLen && ++i == me.length) {
            limit = limit && 1;
        }
    }
    return me;
};

Related Tutorials