줄바꿈할 때 : 역슬러시n을 쓴다.
toUpperCase() : 대문자로 바꿀 때
toLowerCase() : 소문자로 바꿀 때
str.indexOf(text) : 문자가 몇 번째 위치인지 알려준다. 찾는 문자 없으면 -1을 반환
if에서' 0'은 false이니까 항상 1보다 커야 한다.
ex) if (desc,indexOf('Hi')>-1) { }
str.slice(n,m) : 시작점과 끝점. 끝점이 없으면 문자열 끝까지. 음수면 끝에서부터 셈
let desc="abcdefg";
desc.slice(2) //"cdefg"
desc.slice(2,-2)//"cde"
str.substring(n,m)
1.n과m 사이(슬라이스랑 비슷한 면이 있지만, n과m사이 바꿔도 작동)
2.n과 m을 바꿔도 동작함
3.음수는 0으로 인식
let desc="abcdefg";
desc.substring(2,5) ; //"cde"
desc.substring(5,2) ; // "cde"
str.substr(n,m)
n 부터 시작해서 m개를 가져옴
let desc="abcdefg";
desc.substr(2,4) //"cdef"
desc.substr(-4,2) //"de"
str.trim(): 앞뒤 공백 제거
let desc=" coding "
desc.trim(); // "coding"
str.repeat(): n번 반복
let hello="hello";
hello.repeat(3); // "hello!hello!hello!"
문자열 비교
대문자 A의 아스키코드는 65
소문자 a의 아스키 코드는 97
소문자가 대문자보다 크다
문자코드를 -> 숫자로
"a".codePointAt(0); //97
숫자코드를 -> 문자로
String.fromCodePoint(97) //"a"
반대로 숫자 코드를 알고 있으면 문자를 얻어낼 수 있다.
String.fromCodePoint(97) //"a"
예제) 기존 리스트 편집해서 새리스트에 담아서 출력
let list=[
"01. 들어가며",
"02. JS",
"03. css",
"04. html",
"05. 파이썬",
];
let newList=[];
for (let i=0; i<list.length; i++) {
newList.push(list[i].slice(4));
}
console.log(newList);
//금칙어 콜라 넣기
function hasCola(str) {
if (str.indexOf("콜라")) {
console.log("금지 음료");
} else {
console.log("통과");
}
}
hasCola("와 사이다가 나왔네"); //-1
hasCola("보리음료, 삼다수, 콜라가 좋아요");
hasCola("콜라"); //0
-> 제대로 실행하려면 -1보다 크다는 부등호를 넣어야 하거나 index를 확인하지 않는 includes를 쓰면 된다.
정답
function hasCola(str) {
if (str.indexOf("콜라")>-1) {
console.log("금지 음료");
} else {
console.log("통과");
}
}
hasCola("와 사이다가 나왔네"); //
hasCola("보리음료, 삼다수, 콜라가 좋아요");
hasCola("콜라"); //
//금칙어 : 콜라
//includes : 인덱스 확인하지 않고 찾는다. -1을 비교하지 않아도 된다.
//문자가 있으면 true
//문자가 없으면 false 변환
function hasCola(str) {
if (str.includes("콜라")) {
console.log("금지 음료");
} else {
console.log("통과");
}
}
hasCola("와 사이다가 나왔네");
hasCola("보리음료, 삼다수, 콜라가 좋아요");
hasCola("콜라");
'JavsScript' 카테고리의 다른 글
배열에서 쓰는 forEach (0) | 2022.02.20 |
---|---|
배열 메소드-splice,slice,concat (0) | 2022.02.20 |
Math 메소드 (0) | 2022.02.19 |
Symbol : 유일한 식별자 (0) | 2022.02.13 |
객체에서 사용할 수있는 method (0) | 2022.02.13 |