Skip to main content

JavaScript function to format a string just like string.format in C#.

/**
 * Find and replaces a string (search) to another string (replacement) in given
 * string (str).
 *
 * Example:
 * replaceAll('This is a test string', 'is', 'X');
 * >> 'ThX X a test string'
 *
 * @param {string} str
 * @param {string} search
 * @param {string} replacement
 * @return {string}
 */
function replaceAll(str, search, replacement) {
    var fix = search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    return str.replace(new RegExp(fix, "g"), replacement);
}

/**
 * Formats a string just like string.format in C#.
 * https://docs.microsoft.com/en-us/dotnet/api/system.string.format
 *
 * Example:
 * formatString('Hello {0}', 'Tuana');
 * >> 'Hello Tuana'
 *
 * @return {string}
 */
function formatString() {
    if (arguments.length < 1) {
        return null;
    }

    var str = arguments[0];

    for (var i = 1; i < arguments.length; i++) {
        var placeHolder = "{" + (i - 1) + "}";
        str = replaceAll(str, placeHolder, arguments[i]);
    }

    return str;
}