본문 바로가기
Program/java script

자바스크립트 06. 문자열

by Apeach_:) 2020. 12. 15.

 

Achievement Goals

  • 문자열의 속성과 메소드를 이용해 원하는 형태로 만들 수 있다.
    • 문자열의 length라는 속성을 활용해 길이를 확인할 수 있다. str.length
    • 문자열의 글자 하나하나에 접근할 수 있다. str[1]
    • 문자열을 합칠 수 있다. word1 + " " + word2
    • 문자열을 원하는 만큼만 잡을 수 있다. str.substring(0, 3)
    • 영문을 모두 대문자로 바꿀 수 있다. str.toUpperCase
    • 영문을 모두 소문자로 바꿀 수 있다. str.toLowerCase
    • 문자열 중 원하는 글자의 index를 찾을 수 있다 str.indexOf('a')
    • 문자열 중 원하는 글자가 포함되어 있는지 알 수 있다. str.includes('a')

Advanced Challanges

  • 띄어쓰기 (" ") 로 문자열을 구분하여, 배열로 바꿀 수 있다. str.split(" ").join(" ")
  • 위의 배열을 다시 문자열로 바꿀 수 있다.

 

var str = 'codeStates';

console.log(str[0]); //'c'

console.log(str[4]); // 's'

console.log(str[10]); //undefined

 

 

문자열은 읽기만 가능함

새로할당하지 않는한 값이 바뀌지 않음

 

문자열 특징 index로 접근은 가능하지만 쓸 수 없음. 

 

문자열은 +연산자를 쓸수 있음 - 안됨.

 

var str1 = 'code';

var str2 = "states";

var str3 = '1';

 

console.log(str1+str2); //'codestates'

 

.str1.concat(str2,str3...); 형태로 가능

 

**concat 더하는 메소드임

 

length PROPERTY

 

문자열을 전체 길이를 반환

var str = 'codestates';

console.log(str.length); //'10'

 

str.indexOf (searchValue)

arguments:찾고자 하는 문자열

return value 처음으로 일치하는 index, 찾고자 하는 문자열이 없으면 -1

lastindexOf는 문자열 뒤에서 찾음

 

'Blue Whale' .indexOf('Blue'); //0

'Blue Whale' .indexOf('blue'); // -1  없는거기때문

'Blue Whale' .indexOf('Whale'); //5

'Blue Whale Whale' .indexOf('Whale'); //5 처음 등장하는 인텍스만 출력함. 5번째 있음

'canal'.lastIndexOf('a'); //3   lastindexof이기 때문에 a를 뒤에서 찾음 

 

 

str.includes(searchValue)

구형브라우저에서는 안됨

 

'Blue Whale' .includes('blue'); // true  포함된 언어가 있는지에 대해 나옴

 

str.split(seperator)

arguments 분리 기준이 될 문자열

return value 분리된 문자열이 포함된 배열

 

var str ='Hello from the other side';

console.log(str.spit(''));

//

 

csv형식으로 쓰임. 

let csv ='연도,제조사,모델,설명,가격'

 

csv.split(',')

 

csv.split('n')

 

str.substring(start,end)

arguments 시작 index, 끝 index

return value시작과 끝 index사이의 문자열

 

var str = 'abcdefghij';

console.log(str.substring(0,3)); 'abc'

0에서 3까지의 문자열 가져오기

**str.slice(start,end)

substring과 비슷하나 몇가지 차이점이 보임

 

str.toLowerCase() / str.toUpperCase() immutable

argument 없고

대소문자로 바꿔줌.

 

let word = 'hello';

word.toUpperCase()

"HELLO"

 

 

trim 

 

공백문자 : 탭문자 (/t)

, carrige return () 및 문자 

match (advanced)

정규표현식  (advanced)