Skip to content

Instantly share code, notes, and snippets.

@abdelgrib
Last active May 2, 2020 13:38
Show Gist options
  • Save abdelgrib/2fdeb9ac0cce3098e35a31e9218fbb51 to your computer and use it in GitHub Desktop.
Save abdelgrib/2fdeb9ac0cce3098e35a31e9218fbb51 to your computer and use it in GitHub Desktop.
Useful functions in JavaScript
/*Date functions*/
/**
* Returns the number of the current week
* @returns {number} - Number of the current week
*/
Date.prototype.getWeek = function()
{
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
/**
* Determines whether or not a date have a valid format
* @param {date} date - Date to check
* @returns {boolean} - Determine whether or not the date checked is valid
*/
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[1];
var m = matches[2]-1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
/**
* Adds months to a date
* @param {*} date - Date to increment
* @param {*} months - Number of months to add to the initial date entered
*/
function addMonths(date, months)
{
date.setMonth(date.getMonth() + months);
return date.format("dd/MM/yyyy");
}
/*String functions*/
/**
* Remove accented characters
* @param {*} string - Text to format
*/
removeAccentedCharacter = function (value) {
return !value ?
'' :
typeof value === 'string' ?
value
.replace(/\n/g, ' ')
.replace(/á/g, 'a')
.replace(/à/g, 'a')
.replace(/é/g, 'e')
.replace(/í/g, 'i')
.replace(/ó/g, 'o')
.replace(/ú/g, 'u')
.replace(/ê/g, 'e')
.replace(/î/g, 'i')
.replace(/ô/g, 'o')
.replace(/è/g, 'e')
.replace(/é/g, 'e')
.replace(/ï/g, 'i')
.replace(/ü/g, 'u')
.replace(/ç/g, 'c') :
value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment