如何獲取字符串的最後一個字符

我有 php

var id="ctl03_Tabs1";

使用JavaScript,如何得到最後五個字符或最後一個字符? 數組


#1樓

如下腳本顯示使用JavaScript在字符串中獲取最後5個字符和最後1個字符的結果: 瀏覽器

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

輸出: app

Tabs1 //有5個字符 ide

1 //獲得了1個字符 this


#2樓

不要使用.substr() 。 請使用.slice()方法,由於它與跨瀏覽器兼容(請參閱IE)。 spa

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

具備負值的substr()在IE中不起做用 code


#3樓

不須要使用substr方法來獲取字符串的單個字符! ip

以Jamon Holmgren爲例,咱們能夠更改substr方法並只需指定數組位置: element

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

#4樓

若是它是字符串中的最後一個字符,則它將刪除逗號。

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

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

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

}

#5樓

我實際上有如下問題,這就是我如何經過上述答案解決的方法,可是提取id的不一樣方法造成了輸入元素。

我已將輸入附加到

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

而且,當單擊該按鈕時,我只想提取id(即數字)或php ID ($ id)

因此我在這裏作什麼。

$('.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
        });
相關文章
相關標籤/搜索