728x90

✨ pattern과 맞는 String을 교체해주는 helper method

(e.g., str.replace('dog', 'cat')) 왼쪽처럼 dog을 cat으로 교체하는 것이 가능하다.
간단하게 설명하자면,
첫 번째 parameter에는 RegExp(Regular Expressions) 또는 String을 넣을 수 있고(즉, 찾을 pattern)
두 번째 parameter에는 새로 넣을 new string을 넣을 수 있다(즉, 새로 넣을 replacement)

💻Example Code

1) 간단한 단어 교체

const str = 'Hi there!';
const afterReplace = str.replace('Hi', 'Hello');

console.log(afterReplace);

실행 결과(Hi가 Hello로 교체된 것을 볼 수 있다)

2) RegExp를 이용한 교체(alphabet만 남기기)

const strTwo = 'Hi! there~@!';
const afterReplaceTwo = strTwo.replace(/[^\w]/g, '');

console.log(afterReplaceTwo);

실행 결과(특수문자, 공백이 제거된 것을 볼 수 있다)

📌replace(/[^\w]/g, '')를 자세히 살펴보겠다.
1. RegExp의 시작과 끝은 /(slash)
2. []는 []안에 어느 것이라도 매치된다면 이라는 뜻이다. (다시 알아볼 필요가 있음)
3. ^ 는 무효화 시킨다는 뜻이다(반전이라고 생각하면 될듯하다)
4. \w은 글자와 숫자(alphanumeric)를 뜻한다.
5. g는 global이라는 뜻. 한 번 매치되어도 끝까지 매치되는 것을 찾게 한다.

즉, [^\w]을 이용해 글자와 숫자 이외의 모든 문자는 제거한다. 라고 보면 편하다.

😋 Anagrams(철자를 바꾼 말) Algorithm에서 공백, 구두점 그리고 특수문자를 제거하기 위해 사용하였다.
Regular Expressions은 문자열을 다루기에 매우 유용하다. 어렵기 때문에 하나씩 차근차근 쌓아가는 것이 필요하다.

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

 

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

developer.mozilla.org

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

 

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

 

Regular expressions

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), search

developer.mozilla.org

 

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

Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
728x90

✨ object의 keys 또는 values를 array로 반환하는 helper method

💻Example Code

const obj = { a: 'something', b: 2, c: 3 };

console.log( Object.keys(obj) );
console.log( Object.values(obj) );

실행 결과(keys와 values가 array로 반환되는 것을 볼 수 있다)

😋 Anagrams(철자를 바꾼 말) Algorithm 에서 같은 종류의 철자가 사용되었는지 확인할 때 유용하게 사용하였다.
(Algorithm 카테고리의 Anagrams Algorithm 문제에서 확인 가능하다)
이 외에도 다양한 곳에서 사용 가능하다.

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

 

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

 

Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

developer.mozilla.org

 

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

Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
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

Q. 주어진 2개의 String이 서로 Anagrams인지 확인하라 (Anagram - 철자 순서만 다르고, 같은 개수의 알파벳)
(단, 대문자, 공백 그리고 구두점은 제외한다)

--- Examples
anagrams('rail safety', 'fairy tales') --> True
anagrams('RAIL! SAFETY!', 'fairy tales') --> True
anagrams('Hi there', 'Bye there') --> False

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/commit/2cf4631c1d09e038f0bf9827b710812d078c4023

😢 RegExp, Object.keys().length 스킬을 사용하게 될지 예상하기 힘들었다.

😊 Solution 1)
Map을 생성해주는 function을 만들고, Object.keys().length를 이용해 사용된 철자의 종류가 동일한지 확인하고, for ... in을 이용해 사용된 철자의 개수가 동일한지 확인하여 문제를 해결한다.
Solution 2)
순서를 정렬하는 function을 만들고, 그 결과가 서로 같은지 확인하는 방법을 이용해 문제를 해결한다.

위의 2가지 방법에서 가장 중요한 것은 replace(/[^\w]/g, '')을 이용해 대문자, 공백 그리고 구두점을 제거해주는 것이다.

✔ replace(/[^\w]/g, '')

알파벳 외 문자를 제거한다.

✔ toLowerCase()

대문자를 소문자로 바꿔준다

✔ split('')

String을 separator기준으로 Array로 나눠서 저장해준다

✔ sort()

Array의 순서를 UTF-16 기준으로 정렬해준다

✔ join()

Array를 separator기준으로 String으로 합쳐준다

✔ Object.keys()

Object의 key만 Array 형식으로 받아볼 수 있다. 따라서 옆에 .length를 사용해 길이를 받아볼 수 있다

 

Full Code

function anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB);
}
 
function cleanString(str) {
return str
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('');
}
 
// function anagrams(stringA, stringB) {
// const aCharMap = buildCharMap(stringA);
// const bCharMap = buildCharMap(stringB);
//
// if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
// return false;
// }
//
// for (let char in aCharMap) {
// if (aCharMap[char] !== bCharMap[char]) {
// return false;
// }
// }
//
// return true;
// }
//
// function buildCharMap(str) {
// const charMap = {};
//
// for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
// charMap[char] = charMap[char] + 1 || 1;
// }
//
// return charMap;
// }

+ Recent posts