2020년 12월 21일 월요일

HTML 팁

 1. <input>요소에 대한 "자동 완성" 기능을 제공

<input list="animals" name="animal" id="animal">
<datalist id="animals">
<option value="Cat">
<option value="Dog">
<option value="Chicken">
<option value="Cow">
<option value="Pig">
</datalist>

2. color picker
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">

3. progress bar
<label for="course">Course completion:</label>
<progress id="course" value="67" max="100"></progress> 67%

4. meter tag
<label for="disk_g">Disk usage G:</label>
<meter id="disk_g" value="2" min="0" max="10">2 out of 10</meter><br><label for="disk_h">Disk usage H:</label>
<meter id="disk_h" value="0.7">70%</meter>
progress tag는 동적 meter tag는 정적

2020년 12월 15일 화요일

유용한 javascript 문자관련 method들

 endsWith (mozilla.org)

어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 true 혹은 false로 반환한다. 

var str = 'To be, or not to be, that is the question.';

console.log(str.endsWith('question.')); // true
console.log(str.endsWith('to be'));     // false
console.log(str.endsWith('to be', 19)); // true

includes (mozilla.org)

하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 true 또는 false 로 반환합니다.

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false

indexOf (mozilla.org)

호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다. 

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"

console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output: "The index of the 2nd "dog" is 52"
'Blue Whale'.indexOf('Blue');     // returns  0
'Blue Whale'.indexOf('Blute');    // returns -1
'Blue Whale'.indexOf('Whale', 0); // returns  5
'Blue Whale'.indexOf('Whale', 5); // returns  5
'Blue Whale'.indexOf('Whale', 7); // returns -1
'Blue Whale'.indexOf('');         // returns  0
'Blue Whale'.indexOf('', 9);      // returns  9
'Blue Whale'.indexOf('', 10);     // returns 10
'Blue Whale'.indexOf('', 11);     // returns 10

lastIndexOf (mozilla.org)

주어진 값과 일치하는 부분을 fromIndex로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다. 일치하는 부분을 찾을 수 없으면 -1을 반환합니다.

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';

console.log(`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(searchTerm)}`);
// expected output: "The index of the first "dog" from the end is 52"
'canal'.lastIndexOf('a');     //  3 반환
'canal'.lastIndexOf('a', 2);  //  1 반환
'canal'.lastIndexOf('a', 0);  // -1 반환
'canal'.lastIndexOf('x');     // -1 반환
'canal'.lastIndexOf('c', -5); //  0 반환
'canal'.lastIndexOf('c', 0);  //  0 반환
'canal'.lastIndexOf('');      //  5 반환
'canal'.lastIndexOf('', 2);   //  2 반환

match (mozilla.org)

문자열이 정규식과 매치되는 부분을 검색합니다.

var str = 'For more information, see Chapter 3.4.5.1';
var re = /see (chapter \d+(\.\d)*)/i;
var found = str.match(re);

console.log(found);

// logs [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]

// 'see Chapter 3.4.5.1'는 완전한 매치 상태임.
// 'Chapter 3.4.5.1'는 '(chapter \d+(\.\d)*)' 부분에 의해 발견된 것임.
// '.1' 는 '(\.\d)'를 통해 매치된 마지막 값임.
// 'index' 요소가 (22)라는 것은 0에서부터 셀 때 22번째 위치부터 완전 매치된 문자열이 나타남을 의미함.
// 'input' 요소는 입력된 원래 문자열을 나타냄.

matchAll (mozilla.org) ES2020

returns an iterator of all results matching a string against a regular expression, including capturing groups.

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]
const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
  // expected output: "Found football start=6 end=14."
  // expected output: "Found foosball start=16 end=24."
}

padEnd (mozilla.org)

현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 끝(우측)부터 적용됩니다.

const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.'));
// expected output: "Breaded Mushrooms........"

const str2 = '200';

console.log(str2.padEnd(5));
// expected output: "200  "
'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"

replace (mozilla.org)

"cat, cat, cat, bird".replace("cat", (i) => i + "dog"); // returns "catdog, cat, cat, bird"
replaceAll (mozilla.org)
"cat, cat, cat, bird".replaceAll("cat", (i) => i + "dog"); // returns "catdog, catdog, catdog, bird"
search (mozilla.org)
"cat, dog, cat".search("dog"); // returns 5
// With a regex
"cat, dog, cat".search(/dog/g); // returns 5
slice (mozilla.org)
"This is a string I want to slice".slice(27); // returns 'slice'
"This is a string I want to slice".slice(27, 28); // returns 's'
// And we can work backwards with negative values such as
"This is a string I want to slice".slice(-5); // returns "slice"
"This is a string I want to slice".slice(-5, -1); // returns "slic"
startsWith (mozilla.org)
"Hello".startsWith("h"); // true
"Hello".startsWith("e"); // false
// With optional starting index
"Hello".startsWith("e", 1); // true

2020년 12월 7일 월요일

JavaScript Tricks

 

1. Convert string to number

the_string = "123";
console.log(+the_string);
// 123

the_string = "hello";
console.log(+the_string);
// NaN

2. Convert a number to a string

var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string

3. Extract Unique Values

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]

4. Flatten a multidimensional array

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9]

5. Replace All

var example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"

6. Short Circuit Conditionals

if (available) {
addToCart();
}
available && addToCart()

7. Use the length to resize and empty an array

var entries = [1, 2, 3, 4, 5, 6, 7];  
console.log(entries.length);
// 7
entries.length = 4;
console.log(entries.length);
// 4
console.log(entries);
// [1, 2, 3, 4]
var entries = [1, 2, 3, 4, 5, 6, 7]; 
console.log(entries.length);
// 7
entries.length = 0;
console.log(entries.length);
// 0
console.log(entries);
// []

8. Shuffle elements from array

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]

9. Dynamic Property Names

const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }

10. Object values

JavaScript has also introduced the Object.values that returns a single dimension array of the object values.

Have a look at the example below:

const person = {
firstName : "Mehdi",
lastName : "Aoussiad",
age : 19,
eyeColor : "black"
};
console.log(Object.values(person));
// Prints ["Mehdi","Aoussiad",19,"black"]

11. Object entries

The Object.entries are similar to Object.values, but returns a multi-dimension array of the object values and properties(keys).

Here is an example:

const person = {
firstName : "Mehdi",
lastName : "Aoussiad",
age : 19,
eyeColor : "black"
};
console.log(Object.entries(person));
// Prints: [["firstName", "Mehdi"],["lastName", "Aoussiad"],["age", 19],["eyeColor", "black"]]

12. Get the last element of an array
let numbersArr = [4, 8, 9, 34, 100];numbersArr[numbersArr.length - 1]; //return 100// 혹은numbersArr.slice(-1)[0];

13. Random number in a specific range



As you know, we use the method Math.random() to return a random number between 0 and 1.
// Random number between 0 and 4.
Math.floor(Math.random() * 5);
// Random number between 0 and 49.
Math.floor(Math.random() * 50);
// Random number between 0 and 309.
Math.floor(Math.random() * 310);


14. Flattening multi-dimensional array
let arr = [5, [1, 2], [4, 8]];arr.flat(); //returns [5, 1, 2, 4, 8]let twoLevelArr = [4, ["John", 7, [5, 9]]]twoLevelArr.flat(2); //returns [4, "John", 7, 5, 9]


15. Check for multiple conditions

let name = "John";//Bad way.
if(name === "John" || name === "Ben" || name === "Chris"){
console.log("included")
}
//Better way.
if(["John", "Ben", "Chris"].includes(name)){
console.log("included")
}


16. Extract unique values


const languages = ['JavaScript', 'Python', 'Python', 'JavaScript', 'HTML', 'Python'];const uniqueLanguages = [...new Set(languages)];
console.log(uniqueLanguages);
//prints: ["JavaScript", "Python", "HTML"]

17. Run an event only once


If you have an event that you want to only run once, you can use the option once as a third parameter for addEventListener() .

Here is the example:

document.body.addEventListener('click', () => {
console.log('Run only once');
}, { once: true });

As you can see, you just have to set the option to true and the event will only run once.

18. Sum all numbers in an array


let numbers = [6, 9 , 90, 120, 55];numbers.reduce((a, b)=> a + b, 0); //returns 280

19. Sum numbers inside an array of objects

const users  = [
{name: "John", age: 25},
{name: "Chris", age: 20},
{name: "James", age: 31},
]

users.reduce(function(a, b){
return {age: a.age + b.age}
}).age;

20. The keyword “in”


Use the keyword in in JavaScript to check if properties are defined inside an object or if elements are included inside an array for example.
const employee = {
name: "Chris",
age: 25
}
"name" in employee; //returns true.
"age" in employee; //returns true.
"experience" in employee; //retuens false.



21. From number to an array of digits

const toArray = num => [...`${num}`].map(elem=> parseInt(elem))
// 위 구문의 다른 방법// const toArray = num => String(num).split("").map(el=> +el);toArray(1234); //returns [1, 2, 3, 4]
toArray(758999); //returns [7, 5, 8, 9, 9, 9]

Null, undefined and empty checks shorthand

JavaScript multiple conditions shorthand

JavaScript loops shorthand

JavaScript implicit return shorthand

JavaScript spread operator shorthand

JavaScript arrow function shorthand

JavaScript template literals shorthand

JavaScript multi-line string shorthand

JavaScript Array.find shorthand