פונקציות שימושיות ב JS
רשימת פונקציות לשימוש ב JS
Fetch POST to nodejs
let url = "http://localhost:3000/users/login"
fetch(url, {
method:"POST",
body:JSON.stringify(bodyData),
headers: { 'content-type': "application/json"
}
})
.then(resp => resp.json())
.then(data => {
console.log(data)
if(data.token){
localStorage.setItem("tok",data.token)
history.push("/")
}
else{
alert("Worng user or password , try again")
}
})
פונקציה ל SORT של מערך עם אובייקטים לפי פרופ מסויים
function compareValues(key, order = 'asc') {
return function innerSort(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0;
const comparison = a[key].localeCompare(b[key]);
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}
NODEJS Cors solve
app.all('*', function (req, res, next) {
if (!req.get('Origin')) return next();
res.set('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
res.set('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,x-api-key');
next();
});
Regular exp
// בדיקת אנגלית , מספרים וסימנים שונים
const pattern1 = /^[a-zA-Z0-9!@#%&*]{3,9999}$/;
// בדיקת עברית , אנגלית , מספרים בלבד
const pattern2 = /^[0-9 A-Z a-z\u0590-\u05fe]+$/i;
// בדיקת תקינות אימייל תקין
/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i
פונקציה לערבוב מערך
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
פונקציה להוספת פסיק לאחר ספרות האלפים,מליונים וכו'…
function formatMoney(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');;
}
פונקציה ליצירת 6 תווים רנדומלים
const genAbcRandom = (count = 6) => {
let abc_ar = "abcdefghijklmnopqrstuvwxyz1234567890";
let st = "";
for(let i = 0 ; i < count ; i++) {
let rnd = Math.random()*abc_ar.length;
rnd = Math.floor(rnd);
st += abc_ar[rnd];
}
return st;
}
