如何在 jQuery 中获取字符串的子字符串?

jqueryweb developmentfront end technology

要在 jQuery 中获取字符串的子字符串,请使用 substring() 方法。该方法包含以下两个参数:

  • from:from 参数指定子字符串的起始索引。
  • to:to 参数是可选的,它指定提取操作的终止索引。这是一个可选参数,当未指定任何参数时,它将提取剩余的字符串。

示例

您可以尝试运行以下代码来了解如何在 jQuery 中获取字符串的子字符串:

<html>

   <head>
      <title>jQuery subtring</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
            $("#button1").click(function(){
              var str1 = "Hello World!";
              var subStr = str1.substring(0, 5);
              alert(subStr);
            });
         });
      </script>
       
   </head>
   
   <body>
     <p>Hello World!</p>
     <button id="button1">Get substring</button>        
   </body>
   
</html>

相关文章