Nice programing

문자열의 마지막 문자를 어떻게 얻을 수 있습니까?

nicepro 2020. 9. 30. 11:29
반응형

문자열의 마지막 문자를 어떻게 얻을 수 있습니까?


나는 가지고있다

var id="ctl03_Tabs1";

JavaScript를 사용하여 마지막 5 자 또는 마지막 문자를 어떻게 얻을 수 있습니까?


편집 : 다른 사람들이 지적했듯이, 사용 slice(-5)대신에 substr. 그러나 .split().pop()다른 접근 방식에 대해서는이 답변 하단의 솔루션을 참조하십시오 .

원래 답변 :

속성 .substr()과 결합 된 Javascript 문자열 메서드를 사용하고 싶을 것 .length입니다.

var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"

이것은 id.length-5에서 시작하는 문자를 가져오고 .substr ()에 대한 두 번째 인수가 생략되었으므로 문자열의 끝까지 계속됩니다.

.slice()다른 사람들이 아래에서 지적한 것처럼 방법을 사용할 수도 있습니다 .

밑줄 뒤의 문자를 찾으려는 경우 다음을 사용할 수 있습니다.

var tabId = id.split("_").pop(); // => "Tabs1"

이렇게하면 문자열이 밑줄의 배열로 분할 된 다음 배열에서 마지막 요소 (원하는 문자열)가 "팝"됩니다.


사용하지 마십시오 .substr(). .slice()브라우저 간 호환이 가능하므로 대신 방법을 사용 하십시오 (IE 참조).

var id = "ctl03_Tabs1";
id.slice(id.length -5); //Outputs: Tabs1
id.slice(id.length -1); //Outputs: 1

IE에서 작동하지 않는 음수 값을 가진 substr ()


문자열을 배열로 취급 할 수 있으므로 마지막 문자를 얻는 것은 쉽습니다.

var lastChar = id[id.length - 1];

문자열의 섹션을 얻으려면 substr 함수 또는 substring 함수를 사용할 수 있습니다 .

id.substr(id.length - 1); //get the last character
id.substr(2);             //get the characters from the 3rd character on
id.substr(2, 1);          //get the 3rd character
id.substr(2, 2);          //get the 3rd and 4th characters

차이 substrsubstring상기 제 (선택적) 매개 변수를 처리하는 방법이다. 에서는 substr색인 (첫 번째 매개 변수)의 문자 수입니다. 에서는 substring문자 분할이 끝나야하는 위치의 인덱스입니다.


당신은 사용할 수 있습니다 SUBSTR () 메소드를 마지막 n 문자를 검색하는 음의 시작 위치로. 예를 들어, 이것은 마지막 5를 얻습니다.

var lastFiveChars = id.substr(-5);

다음 스크립트는 JavaScript를 사용하여 문자열에서 마지막 5 개 문자와 마지막 1 개 문자를 가져 오는 결과를 보여줍니다.

var testword='ctl03_Tabs1';
var last5=testword.substr(-5); //Get 5 characters
var last1=testword.substr(-1); //Get 1 character

출력 :

Tabs1 // 5 자

1 // 1 개의 문자가 있습니다.


하위 문자열 함수를 확인하십시오 .

마지막 캐릭터를 얻으려면 :

id.substring(id.length - 1, id.length);

substr문자열의 단일 문자를 얻기 위해 메소드 를 사용할 필요가 없습니다 !

Jamon Holmgren의 예를 들어 substr 메서드를 변경하고 단순히 배열 위치를 지정할 수 있습니다.

var id = "ctl03_Tabs1";
var lastChar = id[id.length - 1]; // => "1"

하위 문자열을 다른 문자열의 끝과 비교하고 그 결과를 부울로 사용한다고 가정하면 String 클래스를 확장하여이를 수행 할 수 있습니다.

String.prototype.endsWith = function (substring) {
  if(substring.length > this.length) return false;
  return this.substr(this.length - substring.length) === substring;
};

다음을 수행 할 수 있습니다.

var aSentenceToPonder = "This sentence ends with toad"; 
var frogString = "frog";
var toadString = "toad";
aSentenceToPonder.endsWith(frogString) // false
aSentenceToPonder.endsWith(toadString) // true

If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -

Var x = "hello_world";
 x[0];                    //h
 x[x.length-1];   //d

Yet if you need more than just one character then use splice is effective

x.slice(-5);      //world

Regarding your example

"rating_element-<?php echo $id?>"

To extract id you can easily use split + pop

Id= inputId.split('rating_element-')[1];

This will return the id, or undefined if no id was after 'rating_element' :)


One way would be using slice, like follow:

var id="ctl03_Tabs1";
var temp=id.slice(-5);

so the value of temp would be "Tabs1".


This one will remove the comma if it is the last character in the string..

var str = $("#ControlId").val();

if(str.substring(str.length-1)==',') {

  var stringWithoutLastComma = str.substring(0,str.length-1);    

}

I actually have the following problem and this how i solved it by the help of above answer but different approach in extracting id form a an input element.

I have attached input filed with an

id="rating_element-<?php echo $id?>"

And , when that button clicked i want to extract the id(which is the number) or the php ID ($id) only.

So here what i do .

 $('.rating').on('rating.change', function() {
            alert($(this).val());
           // console.log(this.id);
           var static_id_text=("rating_element-").length;       
           var product_id =  this.id.slice(static_id_text);       //get the length in order to deduct from the whole string    
          console.log(product_id );//outputs the last id appended
        });

var id="ctl03_Tabs1";
var res = id.charAt(id.length-1);

I found this question and through some research I found this to be the easiest way to get the last character.

As others have mentioned and added for completeness to get the last 5:

var last5 = id.substr(-5);

Last 5

var id="ctl03_Tabs1";
var res = id.charAt(id.length-5)
alert(res);

Last

   
 var id="ctl03_Tabs1";
 var res = id.charAt(id.length-1)
alert(res);


The Substr function allows you to use a minus to get the last character.

var string = "hello";
var last = string.substr(-1);

It's very flexible. For example:

// Get 2 characters, 1 character from end
// The first part says how many characters
// to go back and the second says how many
// to go forward. If you don't say how many
// to go forward it will include everything
var string = "hello!";
var lasttwo = string.substr(-3,2);
// = "lo"

I am sure this will work....

var string1="myfile.pdf"
var esxtenion=string1.substr(string1.length-4)

The value of extension will be ".pdf"

참고URL : https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string

반응형