Exercise - JS Core Objects

by Jennifer Piccione

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 (format: YYYY-MM-DD)
 * 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 then returns the modified string
 *
 */

console.clear();

function stringOperations(str) {
    
    var curDate = new Date();
    var year = curDate.getFullYear();
    var month = curDate.getMonth() + 1;
    var day = curDate.getDate();
    var dateString = "";
    if (month < 10) {
        dateString = year + '-' + '0' + month + '-' + day; 
    }
    else {
        dateString = year + '-' + month + '-' + day; 
    }
    //console.log(dateString);
    str = str.replace(/today/,dateString);
    
    var myPiNum = ((Math.PI * 100).toFixed()) / 100;
    str = str.replace(/pi/, myPiNum);
    
    var count = 0;
    for (i=0; i<str.length; ++i) {
        if (str.charAt(i) == 'X') {
            count += 1;   
        }
    }
    console.log("Number of 'X's: ", count);
    return str;
};

var myString = "today is pi dayXXX";
console.log(myString);
newMyString = stringOperations(myString);
console.log(newMyString);