TypeScript - 字串 substr() 方法



此方法返回從指定位置開始,指定數量字元的字串。

語法

string.substr(start[, length]);

引數詳情

  • start − 開始提取字元的位置 (一個介於 0 和字串長度減 1 之間的整數)。

  • length − 要提取的字元數。

注意 − 如果 start 為負數,substr 將其用作從字串末尾開始的字元索引。

返回值

substr() 方法根據給定的引數返回新的子字串。

示例

var str = "Apples are round, and apples are juicy."; 
console.log("(1,2): "    + str.substr(1,2)); 
console.log("(-2,2): "   + str.substr(-2,2)); 
console.log("(1): "      + str.substr(1)); 
console.log("(-20, 2): " + str.substr(-20,2)); 
console.log("(20, 2): "  + str.substr(20,2));

編譯後,它將在 JavaScript 中生成相同的程式碼。

其輸出如下:

(1,2): pp 
(-2,2): y. 
(1): pples are round, and apples are juicy. 
(-20, 2): nd 
(20, 2): d
typescript_strings.htm
廣告
© . All rights reserved.