-
Notifications
You must be signed in to change notification settings - Fork 0
/
JS - Utility.js
210 lines (163 loc) · 4.68 KB
/
JS - Utility.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// JavaScript Utility Functions
// Print console
const { log, info, warn, error } = console;
// querySelector
const select = (selector, scope = document) => {
return scope.querySelector(selector);
};
// addEventListener
const listen = (target, event, callback, ...options) => {
return target.addEventListener(event, callback, ...options);
};
// listen(buttonEl, "click", () => console.log("Clicked!"));
// listen(document, "mouseover", () => console.log("Mouse over!"));
// Random number
const random = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
// console.log( random(1,10) );
/**
* Convert any text into capitalized mode
*
* @param {string} text
* @returns
*/
const capitalizeText = (text) => {
return text.toLowerCase().replace(/(^\w{1})|(\s+\w{1})/g, change => change.toUpperCase());
}
// console.log( capitalizeText('john doe || JOHN DOE') );
/**
* Valid full name
*
* @param {string} value
* @returns
*/
const validateFullName = (value) => {
if (!value) return "This field is empty.";
const regex = /^[a-zA-Z ]+$/;
if (!regex.test(value)) {
return "Invalid full name";
}
return "Valid full name";
};
// console.log( validateFullName('John Doe') );
// console.log( validateFullName('John Doe 007') );
/**
* Valid email address
*
* @param {string} value
* @returns
*/
const validateEmail = (value) => {
if (!value) return "This field is empty.";
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!regex.test(value)) {
return "Invalid email";
}
return "Valid email";
};
// console.log( validateEmail('johndoe@gmail.com') );
/**
* Valid password
*
* @param {string} password
* @returns
*/
const validatePassword = (password) => {
if (!password) return "This field is empty.";
const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+[\]{};':"\\|,.<>/?]).{12,}$/;
if (!regex.test(password)) {
return "Password must contain at least 12 characters, including at least one uppercase letter, one lowercase letter, one number, and one symbol.";
}
return "Valid password";
}
// console.log( validatePassword('John@doe1234') );
/**
* Valid mobile number
*
* @param {string} value
* @returns
*/
const validateMobileNumber = (value) => {
if (!value) return "This field is empty.";
const regex = /^\d{10}$/;
if (!regex.test(value)) {
return "Invalid mobile number";
}
return "Valid mobile number";
};
// console.log( validateMobileNumber(123456789) );
/**
* Truncate Description
*
* @param {string} description
* @param {int} maxLength
* @returns
*/
const getTruncateDescription = (description, maxLength) => {
if (description.length <= maxLength) {
return description;
}
const truncated = description.substring(0, maxLength - 3);
return truncated + '...';
}
// console.log( getTruncateDescription("Lorem, ipsum dolor sit amet consectetur adipisicing elit. Enim error, sapiente eveniet voluptatem repudiandae cum!", 60) );
/**
* Create User-Friendly URLs (Slugify)
*
* @param {string} text
* @returns
*/
function slugify(text) {
return text
.toLowerCase() // Convert to lowercase
.trim() // Remove leading and trailing whitespace
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/[^\w-]+/g, '')// Remove non-word characters except hyphens
.replace(/--+/g, '-'); // Replace consecutive hyphens with a single hyphen
}
// console.log( slugify("JavaScript Utility Functions!") );
/**
* Input Sanitization
*
* @param {string} input
* @returns
*/
const sanitize = (input) => {
const encodedCharacters = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
return input.replace(/[&<>"'/]/g, match => encodedCharacters[match]);
}
// console.log( sanitize('<script>alert("Hello, world!")</script>') );
/**
* Sanitize HTML
*
* @param {string} element
* @returns
*/
const sanitizeHTML = (element) => {
const div = document.createElement("div");
div.textContent = element;
return div.innerHTML;
};
// sanitizeHTML("<h1>Hello, World!</h1>");
/**
* LocalStorage API
*/
const storage = {
get: (key, defaultValue = null) => {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : defaultValue;
},
set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
remove: (key) => localStorage.removeItem(key),
clear: () => localStorage.clear(),
};
// storage.set("data-v1", "Eat, Sleep, Code, Repeat");
// console.log( storage.get("data-v1") );