當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


CoffeeScript String substr()用法及代碼示例


描述

此方法用於返回字符串的必需子字符串。它接受一個整數值,指示子字符串的起始值和字符串的長度,並返回所需的子字符串。如果起始值為負,則substr()方法將其用作字符串末尾的字符索引。

用法

下麵給出的是substr()JavaScript 的方法。我們可以在 CoffeeScript 代碼中使用相同的方法。

string.substr(start[, length])

示例

下麵的例子演示了使用substr()CoffeeScript 代碼中的 JavaScript 方法。將此代碼保存在具有名稱的文件中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;

打開command prompt並編譯 .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);

現在,打開command prompt再次運行 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 String - substr()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。