본문 바로가기
Development (국비 복습 )/JavaScript

String을 객체로 사용하는 경우

by Puddingforever 2022. 9. 21.

string은 보통 기본데이터 primitive value ( 객체가 아니면서 메서드도 가지지 않는 데이터)
로 쓰이지만 new를 집어넣어서 객체로서도 사용될 수 있다.

 

let x = "John";

//typeof x = string 

let y = new String("John");

//typeof y = object




자바스크립트에서 객체는 서로 비교될 수 없다.

let x = new String("John"); //object x 
let y = new String("John"); //object y
document.getElementById("demo").innerHTML = (x==y);
//false , (x===y)로 해도 false로 나옴..객체는 비교될 수 없음



자바스크립트에서 let name = "John";이런 string은 메소드나 property(객체의 특징)이 없기 때문에 객체라고 볼 수 없다.
하지만 String이 메소드를 포함하여 객체로 쓰이는 경우도 있다.

string이 메소드를 사용하여 객체로 쓰이는 경우 

charAt() -> 인덱스 넣어서 문자 찾기
let name = "hello";
let letter = name.charAt(0);
-> h 

length -> 길이 찾기
let txt = "hello";
let length = txt.length;
-> 5 

slice(start,end) -> 문자빼기
0부터 시작하고,첫번째 파라메터는 포함하지만 두번째 파라메터에 있는건 포함X 
let str = "hello";
str.slice(1,2);
-> e
str.slice(0,1)
->h
str.slice(1,3)
->el 

-숫자면 뒤에서부터 체크한다. -인 경우 0부터 카운트 하지말기...
let str = "gurae";
str.slice(-2,-1);
->a 
str.slice(-3,-1);
->ra 

-두번째 파라메터를 빼면, 모두 제거하고 그 제거한 부분만 리턴된다.

let str = "hello";
str.slice(1);
->ello
str.slice(0);
->hello
str.slice(2);
->llo
//-인 경우 0부터 카운트하지 않는다.
str.slice(-5)
->hello
str.slice(-4)
->ello


substr() -> slice()랑 비슷하지만, 두번째 파라메터는 얼마나 자를건지 길이를 정한다.
let str ="hello";
str.substr(1,4);
->hello
두번째 파라메터를 안쓰면 길이 상관없이 다 출력된다.
str.substr(1);
->ello
//-인 경우 뒤에서부터 카운트해준다,-인 경우 1부터 카운트 
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(-4);
->kiwi


replace() -> 문자열 다시 넣어줌
모든 문자를 바꾸고 싶을 때 /g로 넣어줄 수 있음
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");


concat() -> 문자열 합치기
text = "hello" + " " + "world";
text = "hello".concat(" ","world");
둘이 똑같음


trim() ->빈공간 없애줌

'Development (국비 복습 ) > JavaScript' 카테고리의 다른 글

js 배열  (0) 2022.09.21
${변수명} String interpolation 문자열 보간  (1) 2022.09.21
js \ 백래쉬 사용법  (0) 2022.09.20
js 객체 접근법  (1) 2022.09.20
자바스크립트 함수  (0) 2022.09.20

댓글