[Javascript] String.prototype.substring() 메서드

Yuri Lee·2022년 2월 22일
0
post-thumbnail

Intro

현재 진행하는 프로젝트에서 데이터 시간을 UI에 표출해야 했다. 스트링 타입의 데이터를 년/월/일로 자르고 그 사이 사이에 '-'를 넣어주고 싶었고, 이를 위해 substring() 라는 메서드를 활용했다.

String.prototype.substring()

substring() 메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환한다.

Syntax

str.substring(indexStart[, indexEnd])

parameter

  • indexStart : 반환문자열의 시작 인덱스
  • indexEnd(Optional) : 반환문자열의 마지막 인덱스 (포함하지 않음.)

return value

기존문자열의 부분 문자열을 반환한다.

Examples

var anyString = 'Mozilla';

// Displays 'M'
console.log(anyString.substring(0, 1));
console.log(anyString.substring(1, 0));

// Displays 'Mozill'
console.log(anyString.substring(0, 6));

// Displays 'lla'
console.log(anyString.substring(4));
console.log(anyString.substring(4, 7));
console.log(anyString.substring(7, 4));

// Displays 'Mozilla'
console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));

conclusion

이외에도 정규식을 사용해서 표현하는 방법도 있을 것 같다는 생각이 드는군!


https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/substring

profile
Step by step goes a long way ✨

0개의 댓글