Replace All Occurrences of a String in JavaScript


/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
function replaceAll(str, token, newToken, ignoreCase) {
    var i = -1, _token;
    if(typeof token === "string") {
        if(ignoreCase === true) {
            _token = token.toLowerCase();
            while((i = str.toLowerCase().indexOf( _token, i >= 0? i + newToken.length : 0 )) !== -1 ) {
                str = str.substring(0, i)
                        .concat(newToken)
                        .concat(str.substring(i + _token.length));
            }
        } else {
            return str.split(token).join(newToken);
        }
    }
return str;
}