JavaScript 字串 substr() 方法



JavaScript 字串substr()方法用於提取字串的一部分,從指定的索引開始,提取指定數量的字元。

以下是關於substr()方法的一些補充說明:

  • 如果起始索引值大於字串長度,則返回空字串。
  • 如果起始索引值小於零(或為負數),則從字串末尾開始計數。
  • 如果省略或未定義起始索引引數,則將其視為0。
  • 如果長度引數值小於零(或為負數),則返回空字串。
JavaScript 字串 substr() 方法是一個已棄用的方法。此功能不再推薦使用。它可能已從相關的網路標準中刪除。

語法

以下是 JavaScript 字串substr()方法的語法:

substr(start, length)

引數

此方法接受名為“start”和“length”的兩個引數,如下所述:

  • start - 要包含在返回的子字串中的第一個字元的索引(位置)。
  • length (可選) - 要提取的字元數。

返回值

此方法返回一個包含給定字串一部分的新字串。

示例 1

如果省略length引數,則從指定的起始位置開始提取,一直到字串的末尾。

在下面的程式中,我們使用 JavaScript 字串substr()方法從給定的字串“TutorialsPoint”中提取一部分,從指定的起始位置3開始。

<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script>
   const str = "TutorialsPoint";
   document.write("Given string: ", str);
   const start = 3;
   document.write("<br>The start position: ", start);
   //using the substr() method
   var new_str = str.substr(start);
   document.write("<br>The new string: ", new_str);
</script>    
</body>
</html>

輸出

上述程式返回一個新字串“orialsPoint”。

Given string: TutorialsPoint
The start position: 3
The new string: orialsPoint

示例 2

如果我們向此方法傳遞startlength兩個引數,它將從指定的起始位置開始提取字元,並繼續提取給定長度的字元。

以下是 JavaScript 字串substr()方法的另一個示例。我們使用此方法從給定的字串“Hello World”中檢索一部分字串,從指定的起始位置4開始,一直到給定長度的字元8

<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script>
   const str = "Hello World";
   document.write("Given string: ", str);
   const start = 4;
   const length = 8;
   document.write("<br>The start position: ", start);
   document.write("<br>The length of the charcters: ", length);
   //using the substr() method
   var new_str = str.substr(start, length);
   document.write("<br>The new string: ", new_str);
</script>    
</body>
</html>

輸出

執行上述程式後,它將返回一個新字串:

Given string: Hello World
The start position: 4
The length of the charcters: 8
The new string: o World

示例 3

如果 start 引數值超過給定字串的長度,則返回空字串。

在這個例子中,我們使用 JavaScript 字串substr()方法從給定的字串“JavaScript”中提取一部分,從指定的起始位置15開始。

<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script>
   const str = "JavaScript";
   document.write("Given string: ", str);
   const start = 15;
   document.write("<br>The start position: ", start);
   //using the substr() method
   var new_str = str.substr(start);
   document.write("<br>The new string: ", new_str);
</script>    
</body>
</html>

輸出

執行上述程式後,它將返回一個空字串。

Given string: JavaScript
The start position: 15
The new string:
廣告