substring()을 사용해서 문자열 앞에서 또는 뒤에서 자르기를 해본다.

 

 

정의>

substring은 문자열의 시작 인덱스와 종료 인덱스 안의 부분 문자열을 반환한다.

종료 인데스는 옵션이다.

 

*

substr은 문자열의 시작 인덱스에서 크기만큼 가져온다.

 

 

사용법>

str.substring(indexStart[, indexEnd])

 

 

사용예>

1) 앞에서 자르기

var str = "helloworld";

// 앞에서 5 characters

var tmp = str.substring(0, 4);

 

결과>

hello

 

 

2) 뒤에서 자르기

  - 원하는 값이 'world'라면 총길이 10에서 5 실제로 10-5가 적용되면 str.substring(5)

  따라서 시작 인데스값만 적용한다.

 

var str = "helloworld";

// 뒤에서 characters

var tmp = str.substring(str.length-5);

 

결과>

world

 

 

출처>

mozilla 개발자 사이트

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

 

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

 

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

 

+ Recent posts