목차
확장자 mimType 변환
const returnMimeTypes = (extension) => {
let returnMime = '';
const ext = extension.trim().toLowerCase();
if(ext === 'bin'){
returnMime = 'application/octet-stream';
}else if(ext === 'doc'){
returnMime = 'application/msword';
}else if(ext === 'docx'){
returnMime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
}else if(ext === 'epub'){
returnMime = 'application/epub+zip';
}else if(ext === 'gif'){
returnMime = 'image/gif';
}else if(ext === 'htm' || ext === 'html'){
returnMime = 'text/html';
}else if(ext === 'jpg' || ext === 'jpeg'){
returnMime = 'image/jpeg';
}else if(ext === 'js'){
returnMime = 'text/javascript';
}else if(ext === 'json'){
returnMime = 'application/json';
}else if(ext === 'mp3'){
returnMime = 'audio/mpeg';
}else if(ext === 'mp4'){
returnMime = 'video/mp4';
}else if(ext === 'mpeg'){
returnMime = 'video/mpeg';
}else if(ext === 'png'){
returnMime = 'image/png';
}else if(ext === 'pdf'){
returnMime = 'application/pdf';
}else if(ext === 'php'){
returnMime = 'application/x-httpd-php';
}else if(ext === 'ppt'){
returnMime = 'application/vnd.ms-powerpoint';
}else if(ext === 'pptx'){
returnMime = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
}else if(ext === 'svg'){
returnMime = 'image/svg+xml';
}else if(ext === 'txt'){
returnMime = 'text/plain';
}else if(ext === 'xls'){
returnMime = 'application/vnd.ms-excel';
}else if(ext === 'xlsx'){
returnMime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}else if(ext === 'zip'){
returnMime = 'application/zip';
}else if(ext === '7z'){
returnMime = 'application/x-7z-compressed';
}
return returnMime;
}
스크롤 바닥 체크
<input onscroll = "scrollHandle(this)">
const scrollHandle = function(e){
if(!scrollDetect(e)) return;
//스크롤 바닥 일때 실행
}
const scrollDetect = function(event){
const { scrollHeight, scrollTop, clientHeight } = event.target;
const isAtTheBottom = scrollHeight <= Math.ceil(scrollTop) + Math.ceil(clientHeight);
return isAtTheBottom;
}
Object value만 Array에 담음
const setForOfValue = (obj) =>{
const arr = []
for(let[key, value] of Object.entries(obj)){
arr.push(value);
}
return arr;
}
setTimeout Promis 타입으로 변환
const wait = (timeToDelay) => new Promise((resolve) => setTimeout(resolve, timeToDelay));
돈 단위 한국 스타일 포맷
const displayDeposit = (target) => {
var unitWords = ['', '만', '억', '조', '경'];
var splitUnit = 10000;
var splitCount = unitWords.length;
var resultArray = [];
var resultString = '';
var floor = 0;
if(!Number.isInteger(Number(target)) && Number(target) > 0){
floor = Number(target).toFixed(2);
floor = floor.split(".")[1];
}
for (let i = 0; i < splitCount; i++){
var unitResult = (target % Math.pow(splitUnit, i + 1)) / Math.pow(splitUnit, i);
unitResult = Math.floor(unitResult);
if (unitResult > 0){
resultArray[i] = unitResult;
}
}
for (let i = 0; i < resultArray.length; i++){
if(!resultArray[i]) continue;
resultString = String(resultArray[i]) + unitWords[i] + resultString;
}
if(resultString.length == 0 ){
resultString = '0'
}
if(floor > 0){
resultString = `${resultString}.${floor}`
}
return resultString;
};
Jquery Class로 정규식
//숫자만 입력
$(document).on("input", ".onlyNumberInput", function(event) {
$(this).val($(this).val().replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1'));
});
//사용법
<input class="onlyNumberInput">
첨부파일 검증
const fileValidation = (obj) => {
const fileTypes = ['application/pdf', 'image/gif', 'image/jpeg', 'image/png', 'image/bmp', 'image/tif', 'application/haansofthwp', 'application/x-hwp', 'text/plain'];
if (obj.name.length > 100) {
alert("파일명이 100자 이상인 파일은 제외되었습니다.");
return false;
} else if (obj.size > (10 * 1024 * 1024)) {
alert("최대 파일 용량인 10MB를 초과한 파일은 제외되었습니다.");
return false;
} else if (obj.name.lastIndexOf('.') == -1) {
alert("확장자가 없는 파일입니다.");
return false;
} else if (!fileTypes.includes(obj.type)) {
alert("첨부가 불가능한 파일입니다.");
return false;
} else {
return true;
}
}
byte -> mb
const bytesToMegabytes = (bytes) => {
return Math.ceil(bytes / (1024 * 1024) * 100) / 100;
}
휴대폰 번호 하이픈 추가
const addPhoneNmHypen = (value) => {
if (!value) {
return "";
}
value = value.replace(/[^0-9]/g, "");
let result = [];
let restNumber = "";
// 지역번호와 나머지 번호로 나누기
if (value.startsWith("02")) {
// 서울 02 지역번호
result.push(value.substr(0, 2));
restNumber = value.substring(2);
} else if (value.startsWith("1")) {
// 지역 번호가 없는 경우
// 1xxx-yyyy
restNumber = value;
} else {
// 나머지 3자리 지역번호
// 0xx-yyyy-zzzz
result.push(value.substr(0, 3));
restNumber = value.substring(3);
}
if (restNumber.length === 7) {
// 7자리만 남았을 때는 xxx-yyyy
result.push(restNumber.substring(0, 3));
result.push(restNumber.substring(3));
} else {
result.push(restNumber.substring(0, 4));
result.push(restNumber.substring(4));
}
return result.filter((val) => val).join("-");
};
//휴대폰 자동 하이픈
$(document).on("input", ".addPhoneNmHypen", function(event) {
$(this).val(addPhoneNmHypen($(this).val()));
});
/**
* 오늘 기준 지난 1년
* ex) 24-04-13 -> [23-05,23-06,.... , 24-03, 24-04]
* @returns {*[]}
*/
const oldOneYear = () => {
const today = new Date();
const yearArr = [];
let year = String(today.getFullYear()).substring(2);
let month = today.getMonth() + 1;
const addNumlength = (value = 0) => {
if(value < 10){
value = String(value).padStart(2, "0")
}
return value;
}
for(let i = 0; i < 12 ; i++){
if(month === 0){
year = year - 1;
month = 12;
}
yearArr.push(`${year}-${addNumlength(month)}`);
month--;
}
return yearArr.reverse();
}
'JavaScript' 카테고리의 다른 글
[JavaScript] 페이징 (0) | 2024.10.15 |
---|---|
[JavaScript] 드래그 & 드롭 (0) | 2024.04.24 |
[Javascript] 공인 IP 가져오기 (0) | 2023.12.01 |
[JavaScript] 로딩 (0) | 2023.10.12 |
[JavaScript] 정규식 모음 (0) | 2023.09.12 |
확장자 mimType 변환
const returnMimeTypes = (extension) => {
let returnMime = '';
const ext = extension.trim().toLowerCase();
if(ext === 'bin'){
returnMime = 'application/octet-stream';
}else if(ext === 'doc'){
returnMime = 'application/msword';
}else if(ext === 'docx'){
returnMime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
}else if(ext === 'epub'){
returnMime = 'application/epub+zip';
}else if(ext === 'gif'){
returnMime = 'image/gif';
}else if(ext === 'htm' || ext === 'html'){
returnMime = 'text/html';
}else if(ext === 'jpg' || ext === 'jpeg'){
returnMime = 'image/jpeg';
}else if(ext === 'js'){
returnMime = 'text/javascript';
}else if(ext === 'json'){
returnMime = 'application/json';
}else if(ext === 'mp3'){
returnMime = 'audio/mpeg';
}else if(ext === 'mp4'){
returnMime = 'video/mp4';
}else if(ext === 'mpeg'){
returnMime = 'video/mpeg';
}else if(ext === 'png'){
returnMime = 'image/png';
}else if(ext === 'pdf'){
returnMime = 'application/pdf';
}else if(ext === 'php'){
returnMime = 'application/x-httpd-php';
}else if(ext === 'ppt'){
returnMime = 'application/vnd.ms-powerpoint';
}else if(ext === 'pptx'){
returnMime = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
}else if(ext === 'svg'){
returnMime = 'image/svg+xml';
}else if(ext === 'txt'){
returnMime = 'text/plain';
}else if(ext === 'xls'){
returnMime = 'application/vnd.ms-excel';
}else if(ext === 'xlsx'){
returnMime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}else if(ext === 'zip'){
returnMime = 'application/zip';
}else if(ext === '7z'){
returnMime = 'application/x-7z-compressed';
}
return returnMime;
}
스크롤 바닥 체크
<input onscroll = "scrollHandle(this)">
const scrollHandle = function(e){
if(!scrollDetect(e)) return;
//스크롤 바닥 일때 실행
}
const scrollDetect = function(event){
const { scrollHeight, scrollTop, clientHeight } = event.target;
const isAtTheBottom = scrollHeight <= Math.ceil(scrollTop) + Math.ceil(clientHeight);
return isAtTheBottom;
}
Object value만 Array에 담음
const setForOfValue = (obj) =>{
const arr = []
for(let[key, value] of Object.entries(obj)){
arr.push(value);
}
return arr;
}
setTimeout Promis 타입으로 변환
const wait = (timeToDelay) => new Promise((resolve) => setTimeout(resolve, timeToDelay));
돈 단위 한국 스타일 포맷
const displayDeposit = (target) => {
var unitWords = ['', '만', '억', '조', '경'];
var splitUnit = 10000;
var splitCount = unitWords.length;
var resultArray = [];
var resultString = '';
var floor = 0;
if(!Number.isInteger(Number(target)) && Number(target) > 0){
floor = Number(target).toFixed(2);
floor = floor.split(".")[1];
}
for (let i = 0; i < splitCount; i++){
var unitResult = (target % Math.pow(splitUnit, i + 1)) / Math.pow(splitUnit, i);
unitResult = Math.floor(unitResult);
if (unitResult > 0){
resultArray[i] = unitResult;
}
}
for (let i = 0; i < resultArray.length; i++){
if(!resultArray[i]) continue;
resultString = String(resultArray[i]) + unitWords[i] + resultString;
}
if(resultString.length == 0 ){
resultString = '0'
}
if(floor > 0){
resultString = `${resultString}.${floor}`
}
return resultString;
};
Jquery Class로 정규식
//숫자만 입력
$(document).on("input", ".onlyNumberInput", function(event) {
$(this).val($(this).val().replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1'));
});
//사용법
<input class="onlyNumberInput">
첨부파일 검증
const fileValidation = (obj) => {
const fileTypes = ['application/pdf', 'image/gif', 'image/jpeg', 'image/png', 'image/bmp', 'image/tif', 'application/haansofthwp', 'application/x-hwp', 'text/plain'];
if (obj.name.length > 100) {
alert("파일명이 100자 이상인 파일은 제외되었습니다.");
return false;
} else if (obj.size > (10 * 1024 * 1024)) {
alert("최대 파일 용량인 10MB를 초과한 파일은 제외되었습니다.");
return false;
} else if (obj.name.lastIndexOf('.') == -1) {
alert("확장자가 없는 파일입니다.");
return false;
} else if (!fileTypes.includes(obj.type)) {
alert("첨부가 불가능한 파일입니다.");
return false;
} else {
return true;
}
}
byte -> mb
const bytesToMegabytes = (bytes) => {
return Math.ceil(bytes / (1024 * 1024) * 100) / 100;
}
휴대폰 번호 하이픈 추가
const addPhoneNmHypen = (value) => {
if (!value) {
return "";
}
value = value.replace(/[^0-9]/g, "");
let result = [];
let restNumber = "";
// 지역번호와 나머지 번호로 나누기
if (value.startsWith("02")) {
// 서울 02 지역번호
result.push(value.substr(0, 2));
restNumber = value.substring(2);
} else if (value.startsWith("1")) {
// 지역 번호가 없는 경우
// 1xxx-yyyy
restNumber = value;
} else {
// 나머지 3자리 지역번호
// 0xx-yyyy-zzzz
result.push(value.substr(0, 3));
restNumber = value.substring(3);
}
if (restNumber.length === 7) {
// 7자리만 남았을 때는 xxx-yyyy
result.push(restNumber.substring(0, 3));
result.push(restNumber.substring(3));
} else {
result.push(restNumber.substring(0, 4));
result.push(restNumber.substring(4));
}
return result.filter((val) => val).join("-");
};
//휴대폰 자동 하이픈
$(document).on("input", ".addPhoneNmHypen", function(event) {
$(this).val(addPhoneNmHypen($(this).val()));
});
/**
* 오늘 기준 지난 1년
* ex) 24-04-13 -> [23-05,23-06,.... , 24-03, 24-04]
* @returns {*[]}
*/
const oldOneYear = () => {
const today = new Date();
const yearArr = [];
let year = String(today.getFullYear()).substring(2);
let month = today.getMonth() + 1;
const addNumlength = (value = 0) => {
if(value < 10){
value = String(value).padStart(2, "0")
}
return value;
}
for(let i = 0; i < 12 ; i++){
if(month === 0){
year = year - 1;
month = 12;
}
yearArr.push(`${year}-${addNumlength(month)}`);
month--;
}
return yearArr.reverse();
}
'JavaScript' 카테고리의 다른 글
[JavaScript] 페이징 (0) | 2024.10.15 |
---|---|
[JavaScript] 드래그 & 드롭 (0) | 2024.04.24 |
[Javascript] 공인 IP 가져오기 (0) | 2023.12.01 |
[JavaScript] 로딩 (0) | 2023.10.12 |
[JavaScript] 정규식 모음 (0) | 2023.09.12 |