/**
* 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);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.