无涯教程-Javascript - substr()函数

59 阅读1分钟

此方法返回从指定位置开始到指定字符数的字符串中的字符。

substr() - 语法

string.substr(start[, length]);
  • start    -  开始提取字符的-位置(一个介于0和小于字符串长度1之间的整数)。

  • length -  要提取的字符数。

注意-如果Start为负数,则Substr将其用作字符串末尾的字符索引。

substr() - 返回值

substr()方法根据给定的参数返回新的子字符串。

substr() - 示例

<html>
   <head>
      <title>JavaScript String substr() Method</title>
   </head>
   
   <body>   
      <script type="text/javascript">
         var str="Apples are round, and apples are juicy.";         
         document.write("(1,2): "    + str.substr(1,2));
         document.write("<br />(-2,2): "   + str.substr(-2,2));
         document.write("<br />(1): "      + str.substr(1));
         document.write("<br />(-20, 2): " + str.substr(-20,2));
         document.write("<br />(20, 2): "  + str.substr(20,2));
      </script>      
   </body>
</html>

运行上面代码输出

(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d

参考链接

www.learnfk.com/javascript/…