jQuery를 사용하여 문자열에서 마지막 문자를 삭제하는 방법은 무엇입니까? 4할 때 문자열에서 마지막 문자를 삭제하는

예를 들어 123-4-삭제 4할 때 문자열에서 마지막 문자를 삭제하는 방법 은 jQuery를123- 사용하여 표시해야합니다 .



답변

당신은 또한 일반 자바 스크립트에서 이것을 시도 할 수 있습니다

"1234".slice(0,-1)

음의 두 번째 매개 변수는 마지막 문자와의 오프셋이므로 -2를 사용하여 마지막 2자를 제거 할 수 있습니다.


답변

왜 이것을 위해 jQuery를 사용 하는가?

str = "123-4";
alert(str.substring(0,str.length - 1));

물론 당신이해야한다면 :

jQuery를 포함한 Substr :

//example test element
 $(document.createElement('div'))
    .addClass('test')
    .text('123-4')
    .appendTo('body');

//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));

답변

@skajfes와 @GolezTrol은 사용하기 가장 좋은 방법을 제공했습니다. 개인적으로 “slice ()”를 선호합니다. 코드가 적으므로 문자열의 길이를 알 필요가 없습니다. 그냥 사용하십시오 :

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

답변

일반 JavaScript로 할 수 있습니다 :

alert('123-4-'.substr(0, 4)); // outputs "123-"

문자열의 처음 네 문자를 반환합니다 ( 4필요에 맞게 조정 ).