JavaScript 中的 substr() 和 substring() 有什么区别?

javascriptweb developmentfront end technology

上面给出的示例具有相同的输出,但是方法不同,参数也不同。

substring() 方法的第二个参数是停止搜索的索引,而 substr() 的第二个参数是返回的最大长度。

示例

让我们看一个 JavaScript 中 substr() 方法的示例 −

<html>
   <head>
      <title>JavaScript String substr() Method</title>
   </head>
 
   <body>
      <script>
         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>

示例

让我们看一个 JavaScript 中 substring() 方法的示例 −

<html>
   <head>
      <title>JavaScript String substring() Method</title>
   </head>

   <body>
      <script>
         var str = "Apples are round, and apples are juicy.";
         document.write("(1,2): " + str.substring(1,2));
         document.write("<br />(0,10): " + str.substring(0, 10));
         document.write("<br />(5): " + str.substring(5));
      </script>
   </body>
</html>

相关文章


有用资源