728x90

✨ 내가 찾고자하는 Pattern(character or string etc)을 찾기에 유용한 helper method
(Pattern은 사실 Regular Expression(정규표현식)이지만 쉽게 표현하기 위해 사용하였다)

💻Example Code

const str = 'Hi There!!';
const matches = str.match(/[aeiou]/gi);

console.log( matches );
console.log( matches ? matches.length : 0 )

실행 결과(match된 내용과 배열의 길이)

😋 특히, 특정 문자열을 검색하는 알고리즘 문제를 풀거나, 개발을 할때 매우 유용하다. (단, RegExp를 잘 안다는 전제하에)
Vowels Algorithm(모음 찾기) 문제를 풀 때 잘 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match()

The match() method retrieves the result of matching a string against a regular expression.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
728x90

Q. 입력받은 string에서 vowels(모음 - a, e, i, o, u)가 몇 개인지 찾아내라.

--- Examples
vowels('Hi There!') --> 3
vowels('Why do you ask?') --> 4
vowels('Why?') --> 0

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/405d27e61383b84dca83ff1716f9ca74276a2a7f/exercises/vowels/index.js

😢 vowels를 손쉽게 찾도록 도와줄 includes, match를 활용하는 것이 익숙하지 않았다.

😊 Solution 1)
checker array에 모음(a, e, i, o, u)
를 미리 저장해두고, for ... of loop안에서 checker.includes()를 이용해 모음이 있다면 count를 증가시키면서 모음의 개수를 찾아냈다. for ... of는 여러모로 참 유용하다.

Solution 2)
match
helper method안에 RegExp를 삽입하여 매우 간단하게 모음을 찾아냈다.
입력받은 str에 match를 사용해주면, 만약 원하는 값이 match됐을 때, 그 값이 반환된다.
여기서 중요한 것은 RegExp에서 g를 넣어줘야 global로 끝까지 검색을 하여 match된 모든 값의 배열을 반환해주며, i를 넣어줘야 대소문자 구분없이 match를 확인해준다.

✔ Array.prototype.includes()

Array에 있는 값들 중에 includes()괄호 안에 넣어준 값을 포함하고 있나? 확인해준다.

✔ String.prototype.match()

String(문자열)에 있는 character중에 match(RegExp)괄호 안에 있는 RegExp의 조건과 매치되는 값이 있나? 확인해준다.

✔ /[aeiou]/gi

[a, e, i, o, u]중에 하나라도 있으면 체크된다.
g는 global search(한 번 매치되고 끝나지 않고, 끝까지 체크한다)
i는 case-insensitive search 대소문자 구분없이 같은 알파벳이라면 동일하게 체크된다.

Full Code

function vowels(str) {
const matches = str.match(/[aeiou]/gi);
return matches ? matches.length : 0;
}
 
// function vowels(str) {
// let count = 0;
// const checker = ['a', 'e', 'i', 'o', 'u'];
 
// for (let char of str.toLowerCase()) {
// if (checker.includes(char)) {
// count++;
// }
// }
 
// return count;
// }
728x90

✨ String의 알파벳을 대문자(toUpperCase()) 또는 소문자(toLowerCase())로 바꿔주는 helper method

(e.g., str.toLowerCase() or str.toUpperCase()) 왼쪽처럼 String 변수에 helper method를 붙여 사용한다.

💻Example Code

const strOne = 'abc';
const strTwo = 'ABC';

console.log( strOne.toUpperCase() );
console.log( strTwo.toLowerCase() );

실행 결과(소문자는 대문자로, 대문자는 소문자로 바뀐 걸 볼 수 있다)

😋 Anagrams(철자 순서를 바꾼 말)와 Vowels(모음 찾기) Algorithm 에서 유용하게 사용했다. 다양한 곳에서 활용이 가능하다.
활용된 내용은 위의 알고리즘 문제를 참고하시면 좋습니다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

 

String.prototype.toLowerCase()

The toLowerCase() method returns the calling string value converted to lower case.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

 

String.prototype.toUpperCase()

The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
728x90

✨ 열거 가능한 성질의 object의 key를 반복하기 위한 for loop

💻Example Code

const charMap = { a:1, b:2, c:3 };

for(let char in charMap) { console.log(`${char}: ${charMap[char]}`) };

실행 결과(object key를 하나씩 출력)

😋 Map Object 또는 열거 가능한 Object에 대한 반복문을 사용하고 싶을 때 사용 가능하다.
Max Char(가장 많이 쓰인 문자 찾기), Vowels(모음 개수 찾기) 등 Algorithm에서 확인 가능하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

'JavaScript > Grammar' 카테고리의 다른 글

Conditional (ternary) operator(삼항 조건 연산자)  (0) 2019.12.30
for...of  (0) 2019.12.27
728x90

✨ Array에 내가 입력한 값(String or Number etc.)이 포함되어 있는지 확인할 때 사용하는 helper method

(e.g., strArr.includes('a')) 왼쪽처럼 strArr이라는 Array에 'a'가 있다면 true, 없다면 false를 return.
Vowels(모음 찾기) Algorithm에서 유용하게 사용하였다.

 

💻Example Code

const strArr = [ 'a', 'b', 'c' ];

console.log( strArr.includes('a') );

실행 결과( 'a'가 포함되어있기 때문에 true 출력 )

😋 Vowels(모음 찾기) Algorithm을 풀 때, 주어진 String에서 모음(a, e, i, o, u)이 몇 개인지 찾을 때 매우 유용하다.
더 활용된 내용은 Algorithm 카테고리의 Vowels(모음 찾기) Algorithm을 참고하시면 됩니다. 

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24

+ Recent posts