Wednesday, 29 May 2013

JavaScript - String Extensions #2 [ replaceAll() ]

Unfortunately function replace() in JavaScript replaces only the first matching SubString.
Here is an extension of String Type, which allows you to replace all the found SubStrings.
You can optionally specify more than one (array of strings) string to search for.
/****************************************
* String extensions
****************************************/
String.prototype.replaceAll = function (search, replace) {
    /// 
    /// Replaces all instances of [search] String or Array of Strings
    /// 

    var searches = [];
    if (Object.prototype.toString.call(search) === '[object Array]') {
        searches = search;
    } else {
        searches = [search];
    }
    var result = this + "";
    for (var i = 0; i < searches.length; i++) {
        result = result.split(searches[i]).join(replace);
    }

    return result;
};

Usage of simple replace:
var someString = "aaa-bbb-ccc-ddd";
var resultCsv = someString.replaceAll("-", ";");

Replace array of strings:
var someString = "aaa-bbb#ccc:ddd";
var resultCsv = someString.replaceAll(["-", "#", ":"], ";");