All'alba vincerò

At dawn, I will win!

Javascript

[JS] 문자열 메서드

나디아 Nadia 2024. 6. 14. 19:24

 

문자열의 길이

  • 공백 포함
let message = 'Less is more.';

let stringTotalLength = message.length;
console.log(stringTotalLength); // 13

 

 

 

특정 index의 글자 추출

  • 공백 미포함
let message = 'Less is more.';

let extractCharacter = message[5];
console.log('extractCharacter : ', extractCharacter) // i

 

 

 

문자열 중간 글자를 바꾸는 건 불가능 

  • 기존 문자 변경 대신, 새로운 문자를 생성해야 함
let immutableChangeCharacter = 'P' + message.slice(1);

console.log(message);

 

 


 

부분 문자열 추출

 

slice(start [, end])

: start와 end 사이에 있는 문자열을 반환

  • 음수 허용
let message = 'Less is more.';

let slice = message.slice(4, -1);
console.log('slice : ', slice) // is more

 

 

 

substring(start [, end])

: start와 end 사이에 있는 문자열을 반환

  • slice와 아주 유사하지만 start가 end보다 커도 괜찮다.
  • 음수 미허용 (0으로 취급)
let message = 'Less is more.';

let subString = message.substring(2, 5);
console.log('subString : ', subString) // ess

 

 

 

substr(start [, length])

: start에서부터 시작해 length개의 글자를 반환

  • 길이를 기준으로 문자열을 추출
let str = "stringify";

alert( str.substr(2, 4) ); // ring

 

 


 

문자열 포함 여부 확인

 

indexOf()

: 해당 문자열의 위치를  반환

  • 없으면 -1 반환
let message = 'Less is more.';

let indexOf = message.indexOf('is');
console.log('indexOf : ', indexOf)

//-----------------------------------

// 사용 브라우저를 체크하는 함수
function checkBrowser() {

  const agent = window.navigator.userAgent.toLowerCase();
  let browserName;

  switch (true) {
    case agent.indexOf('edg') > -1:
      browserName = 'MS Edge'
      break;
    case agent.indexOf('chrome') > -1 && !!window.chrome:
      browserName = 'Chrome'
      break;
    case agent.indexOf('safari') > -1:
      browserName = 'Safari'
      break;
    case agent.indexOf('firefox') > -1:
      browserName = 'Firefox'
      break;
    case agent.indexOf('trident') > -1:
      browserName = 'IE'
      break;
    default:
      browserName = '무슨 브라우저 쓰세요..?'
  }

  return browserName
}

checkBrowser() // 'Chrome'

 

 

 

lastIndexOf(substr, position)

: 문자열 끝에서부터 해당 문자열의 위치를 반환 

let message = 'Less is more.';

let lastIndexOf = message.lastIndexOf('s');
console.log('lastIndexOf', lastIndexOf) // 6

 

 

 

includes()

: 해당 문자열의 포함 여부 반환

  • boolean형
let message = 'Less is more.';

let includes = message.includes('Less')
console.log('includes', includes) // true

 

 

 

startsWith()

: 해당 문자열로 시작하는 지의 여부 반환

  • boolean형
let message = 'Less is more.';

let startsWith = message.startsWith('less')
console.log('startsWith', startsWith) // false

 

 

 

endsWith()

: 해당 문자열로 끝나는 지의 여부 반환

  • boolean형
let message = 'Less is more.';

let endsWith = message.endsWith('more')
console.log('endsWith', endsWith) // false

 

 


 

문자열 공백 제거

 

trimStart()

: 시작 부분 공백 제거 

let str = '         a      b    c          d           '

let trimStart = str.trimStart();
console.log('trimStart', trimStart);
// a      b    c          d

 

 

 

trimEnd()

: 끝 부분 공백 제거 

let str = '         a      b    c          d           ';

let trimEnd = str.trimEnd();
console.log('trimEnd', trimEnd);
//          a      b    c          d

 

 

 

trim()

: 양쪽 공백 제거

let str = '         a      b    c          d           ';

let trim = str.trim();
console.log('trim', trim);
// a      b    c          d

 

 

 

 

모든 공백 제거 (중간 공백 포함)

1. replaceAll()

let str = '         a      b    c          d           '

const replaceAll = str.replaceAll(' ', '')
console.log('replaceAll', replaceAll) // abcd

 

 

2. 정규 표현식

let str = '         a      b    c          d           '

const replace = str.replace(/\s*/g, '')
console.log('replace', replace) // abcd

 

 

3. 함수

let str = '         a      b    c          d           '

const trimText = (str) => str.replace(/\s*/g, '')
console.log(trimText(str)); // abcd

 

 


 

기타 함수

 

repeat()

: 텍스트 반복

let message = 'Less is more. ';

let repeat = message.repeat(3);
console.log('repeat', repeat) // Less is more. Less is more. Less is more.

 

 

 

toLowerCase()

대문자를 소문자 변환 

alert( 'Interface'.toLowerCase() ); // interface

 

 

 

toUpperCase()

문자를 대문자로 변환 

alert( 'Interface'.toUpperCase() ); // INTERFACE

 

 


 

텍스트 이름 변환 유틸리티 함수

 

카멜 케이스(Camel Case)

let message = 'Less is more.';

function toCamelCase(string) {
  return string.replace(/(\s|-|_)+./g, ($1) => $1.trim().replace(/(-|_)+/, '').toUpperCase())
}

console.log('toCamelCase', toCamelCase(message)) // LessIsMore.

 

 

 

파스칼 케이스(Pascal Case)

let message = 'Less is more.';

function toPascalCase(string) {
  let name = toCamelCase(string);
  return name[0].toUpperCase() + name.slice(1);
}

console.log('toPascalCase', toPascalCase(message)) // LessIsMore.

 

 


 

 

문자열

 

ko.javascript.info