CoffeeScript 字串 - substr()



說明

此方法用於返回字串所需的部分字串。它接受一個整數值,表示部分字串的起始值和字串的長度,並返回所需的部分字串。如果起始值是負數,則 substr() 方法將其用作字串結尾的字元索引。

語法

下面給出了 JavaScript 的 substr() 方法的語法。我們可以在 CoffeeScript 程式碼中使用相同的方法。

string.substr(start[, length])

示例

以下示例演示了在 CoffeeScript 程式碼中使用 JavaScript 的 substr() 方法。將此程式碼儲存在名為 string_substr.coffee 的檔案中

str = "Apples are round, and apples are juicy.";
         
console.log "The sub string having start and length as (1,2) is : " + str.substr 1,2
console.log "The sub string having start and length as (-2,2) is : " + str.substr -2,2
console.log "The sub string having start and length as (1) is : " + str.substr 1
console.log "The sub string having start and length as (-20, 2) is : " + str.substr -20,2
console.log "The sub string having start and length as (20, 2) is : " + str.substr 20,2;

開啟 命令提示符 並編譯 .coffee 檔案,如下所示。

c:\> coffee -c coffee string_substr.coffee

在編譯時,它會給你以下 JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var str;

  str = "Apples are round, and apples are juicy.";

  console.log("The sub string having start and length as (1,2) is : " + str.substr(1, 2));

  console.log("The sub string having start and length as (-2,2) is : " + str.substr(-2, 2));

  console.log("The sub string having start and length as (1) is : " + str.substr(1));

  console.log("The sub string having start and length as (-20, 2) is : " + str.substr(-20, 2));

  console.log("The sub string having start and length as (20, 2) is : " + str.substr(20, 2));

}).call(this);

現在,再次開啟 命令提示符 並執行 CoffeeScript 檔案,如下所示。

c:\> coffee string_substr.coffee 

在執行時,CoffeeScript 檔案會產生以下輸出。

The sub string having start and length as (1,2) is : pp
The sub string having start and length as (-2,2) is : y.
The sub string having start and length as (1) is : pples are round, and apples are juicy.
The sub string having start and length as (-20, 2) is : nd
The sub string having start and length as (20, 2) is : d
coffeescript_strings.htm
廣告