[JS : 변수의 전달, 문자열 다루기]

Teasan·2020년 9월 27일
0

JavaScript

목록 보기
1/15
post-thumbnail

<변수의 전달>

Javascript 에는 두가지 종류의 변수타입이 있다.
(MDN 참고 https://developer.mozilla.org/ko/docs/Glossary/Primitive)

primitive types 예제

let a = 13 // assign '13' to 'a'
let b = a // copy the value of 'a' to 'b' 
b = 37 // assign '37' to 'b'
 console.log(a) // ==> 13

reference types 예제

let a = {c:13} // assign the reference of new object to 'a'
let b = a // copy the reference of the object inside 'a' to new variable 'b'
b.c = 37 // modify the contents of the object 'b' refers to 
 console.log(a) // ==> {C:37}

<문자열 다루기 : String methods>

문자열string은 텍스트 형태로 표현될 수 있는 데이터를 보관하는데 유용하다.
문자열에서 개개의 문자에 접근하는 방법은 두가지가 있다.
(MDN 참고 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String)
a. charAt( ) methods

return 'cat'.charAt(1); // returns "a"

b. str[index]

return 'cat'[1]; // returns "a"

✦ index로 개개인의 문자에 접근은 가능하지만 속성을 바꾸거나 쓸 수는 없다. (read only)

CONCATENATING STRINGS

  • 연산자를 쓸 수 있으며, string 타입과 다른 타입 사이에 + 연산자를 쓰면, string 형식으로 변환(toString) 된다.
  • 일반적으로 toString() 함수를 많이 사용하고 있지만 toString의 "안전한" 대안으로 String을 사용할 수 있다.
  • null과 undefined에서도 잘 동작한다.

<str.methods>

str.length

  • 문자열의 전체 길이를 반환
var str = 'CodeStates' ;
console.log(str.length) ; // 10

str.indexOf

  • 호출한 String 객차에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다.
    일치하는 값이 없으면 -1 을 반환한다.
  • see more : lastIndexOf 는 문자열 뒤에서부터 첫 번째 인덱스를 반환한다.
'Blue Whale'.indexOf('Blue') ; // 0 ('Blue'라는 문자열이 앞에서 0번째부터 나오기 때문)
'Blue Whale'.indexOf('blue') ; // -1 (찾고자 하는 문자열이 없기 때문)
'Blue Whale'.indexOf('Whale') ; // 5 ('Whale'이라는 문자열이 앞에서 5번째부터 나오기 때문)
'Blue Whale Whale'.indexOf('Whale') ; // 5 ('Whale'이라는 문자열이 5번째부터 나오기 때문)
'canal'.lastIndexOf('a') ; // 3 ('a'라는 문자열이 뒤에서 3번째부터 나오기 때문)

str.includes(searchValue)

  • 하나의 문자열이 다른문자열에 포함되어 있는지를 판별하고, 결과를 Boolean(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

str.split(seperator)

  • String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다. 분리만 가능.
var str = '대표님 퇴근 좀 빨리 시켜주세요' ;
console.log(str.split(' '));
// ['대표님', '퇴근', '좀', '빨리', '시켜주세요']

str.substring(start, end)

  • 문자열에서 특정 위치에서 시작하여 특정 문자 수 만큼의 문자들을 반환한다.
    시작start과 끝end index 사이의 문자열을 말하며, end를 지정할 때는 원하는 index 순서 바로 전까지 자른다.
var str = 'abcdefghij';
console.log(str.substring(0, 3)) ; // 'abc'
console.log(str.substring(3, 0)) ; // 'abc' (시작start 과 끝end 순서가 달라도 상관 없다. 작은 수가 start, 큰 수가 end)
console.log(str.substring(1, 4)) ; // 'bcd'
console.log(str.substring(-1, 4)) ; // 'abcd' (음수는 0번째로 취급한다)
console.log(str.substring(0, 3)) ; // 'abcdefghij' (index 범위가 넘을 경우 마지막 번째 index로 취급)

str.slice

  • 문자열의 일부를 추출하여 문자열의 원본을 수정하지 않고, 새로운 문자열로 반환한다.
  • Arguments : start시작 / end끝 index
    • end : number의 숫자가 잘라내는 범위의 index 숫자보다 작아야 한다.
  • Return value : new array element return
  • index의 범위만큼 element를 추출
  • 배열의 특정한, 원하는 부분만 return하는 함수
{
    const array = [1, 2, 3, 4, 5];
    const result = array.slice(0, 2);
    console.log(result);
    // (2) [1, 2]
    console.log(array);
    // (5) [1, 2, 3, 4, 5]
    // array는 변하지 않음.
}

str.toLowerCase( ) / str.toUpperCase( ) : IMMUTABLE

  • str.toLowerCase( ) : 소문자로 변환
  • str.toUpperCase( ) : 대문자로 변환
var sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toLowerCase());
// expected output: "the quick brown fox jumps over the lazy dog."
console.log(sentence.toUpperCase());
// expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

str.trim( )

var orig = '   foo  ';
console.log(orig.trim()); // 'foo'
// 한 쪽의 공백만 제거하는 .trim() 예제
var orig = 'foo    ';
console.log(orig.trim()); // 'foo'

str.match(advanced)

var paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
var regex = /[A-Z]/g;
var found = paragraph.match(regex);
console.log(found);
// expected output: Array ["T", "I"]

str.replace(advanced)

var p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
var regex = /dog/gi;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
profile
일단 공부가 '적성'에 맞는 개발자. 근성있습니다.

0개의 댓글