티스토리 뷰
문자열에서 index란? str[index]
index의 사전적 의미는 색인.
하지만 색인이라고 하면 이해하고 받아들이기가 어려웠다.
index 를 주소라고 생각하자.
sophie[0] = 's'
sophie라는 문자열의 0번째 주소는? 's' (letter로 출력!)
결국 str[index] 에서, index에는 숫자가 들어가며, 나오는 결과값은 character가 된다.
Index는 0부터 시작이된다.
let name = 'sophie';
console.log(name[0]) // s
console.log(name[1]) // o <- nmae[1]은 보다시피 s 가아닌 o 이다.
console.log(name[2]) // p
str[index] = readonly Immutable
위의 내용을 잘 기억해야 하는 이유!
하기의 문제를 보자(반복문)
문제 : 문자열과 두 개의 문자(from, to)를 입력받아, 문자열에 등장하는 특정 문자(from)가 다른 문자(to)로 바뀐 문자열을 리턴해야 합니다.
이 문제에서 나는 아래와 같은 코드를 사용했다.
function replaceAll(str, from, to) {
// TODO: 여기에 코드를 작성합니다.
let result ='';
for(let i=0; i<str.length; i++){
if(str[i] === from){
str[i] = to // 그다음에 result값은 계속 더한값
result = result +[i] // 뭔가 이상하다
}else{
result = result + str[i];
}
}
return result;
}
위 코드가 불가능한 이유는? => str[index] 의 값은 Immutable하기 때문에.
**이런 이유때문에 자주 사용되는 메소드의 특징은 이해한 후 까먹지 않게 외워야한다.
문자열의 연산
문자열에서 + 는 연산이라는 의미가 아니다.
'+' 는 이어준다는 의미로 사용된다.
- 문자열과 문자열을 합한것 'sophie'+'coding' = 'sophiecoding'
- 문자열과 숫자의 정렬 'sophie'+1105 = 'sophie1105' 자바스크립트에서 문자열+다른타입 => 문자열이된다
Str 메소드
- str. length : str의 길이 -> number로 출력
let name='sophie'
console.log(name.length)// <-이 값은 6
- str.substring(start,end) -> string으로 출력
let name = 'sophiecoding';
console.log(name.substring(2,5));// phi 가 출력
!!!
str.substring(num) 일시 start가 num이되어 num부터 str의 끝까지 출력된다.
let name = 'sophiecoding';
console.log(name.substring(5)); // ecoding
- str.indesOf(찾고자하는 문자열) -> 처음으로 일치하는 index , 찾고자하는 문자열이 없으면 -1로 출력
'sophie coding'.indexOf('soph') // 0
'sophie coding'.indexOf('odi') // 8
- str.toUpperCase() , str.toLowerCase;
console.log('sophie'.toUpperCase()); //SOPHIE
console.log('soPHIe'.toLowerCase()); //sophie