Exercise - JS Core Objects

by Kaushik Ruparel

JavaScript

/**
 * String manipulation
 *
 * Create a function that takes a string and performs some operations on it.
 *
 * The function should:
 *
 * 1) Replace the word "today" with the current date
 * 2) Replace the word "pi" with the numeric value of PI, to the 2nd decimal place
 * 3) Count how many occurrences of the letter X there are and output the count to the console
 *
 * It should then return the modified string.
 *
 */

/*var str = "today is pi day";
str = str.replace("today", "now");
str = str.replace("pi", Math.round(Math.PI * 100) / 100);

console.log(str);

*/
function stringFun(str) {
    var today = Date.now().toString(),
        count = 0;

    var result = str.replace(/\b\w+\b/g, function (word) {
        count += (word.match(/x/gi) || []).length;

        switch (word) {
            case "today":
            case "Today":
                return today;
            case "pi":
            case "Pi":
                return Math.round(Math.PI * 100) / 100;

            default:
                return word;
        }


    });

    console.log("number of x chars is " + count);
    return result;
}

var a = stringFun("today is xoxo pi day");
console.log(a);