📜  JavaScript 中 substr() 和 substring() 的区别

📅  最后修改于: 2022-05-13 01:56:19.357000             🧑  作者: Mango

JavaScript 中 substr() 和 substring() 的区别

这两个函数都用于获取字符串的指定部分,但它们之间存在细微差别。 str.substr()函数: str.substr()函数从给定字符串的指定索引返回指定数量的字符。句法:

str.substr(start, len)

参数:

  • start:必填参数。它指定开始提取的位置。第一个字符的索引为 0。如果 start 参数为正且大于或等于 str 的长度,则此函数返回一个空字符串。如果 start 参数为负数,则此函数将其用作字符串末尾的索引。如果 start 参数为负数或大于字符串的长度,则 start 参数设置为 0。
  • len:可选参数。它指定要提取的字符数。如果未通过,则提取整个字符串。

str.substring()此方法从字符串中获取两个指定索引之间的字符,并返回新字符串。句法:

str.substring(start, end)

参数:

  • start:必填参数。它指定开始提取的位置。第一个字符的索引为 0。
  • end:可选参数。它指定结束提取的位置(最多,但不包括)。如果不使用,它会提取整个字符串。

示例 1:此示例对两个函数仅使用一个参数并产生相同的输出。

HTML


 

    
        Difference between substr()
        and substring() function
    

 

     
    

        GeeksForGeeks     

          

                       

              


html


 

    
        JavaScript | Difference between
        substr() and substring() function
    

 

     
    

        GeeksForGeeks     

          

                       

              


输出:

  • 在点击按钮之前:
  • 点击按钮后:

示例 2:此示例对两个函数都使用参数(3, 7)并返回输出。

html



 

    
        JavaScript | Difference between
        substr() and substring() function
    

 

     
    

        GeeksForGeeks     

          

                       

                                  

输出:

  • 在点击按钮之前:
  • 点击按钮后:

让我们以表格形式了解差异 - :

 substr()substring()
1.It is used to extract a part of the stringIt is used to extract a substring in a string
2.It takes parameters as starting index of the part which we want to extract and the length till which we want to extract the string part.Its parameters are the start and end position of the substring that  we want to extract
3.

Syntax -:

string.substr(start, length)

Syntax – :

string.substring(start, end)

4.It does not distort the original stringIt is also an in-built string method in Javascript.
5.It is also an in-built string method in Javascript.It does not distort the original string
6.Its return type value is of type string.Its return value is of type string
7.It is an ECMAScript1 feature.It is an ECMAScript1 feature.
8.Its supported browsers are -: chrome , safari, Microsoft edge , firefox , Internet Explorer , operaIts supported browsers are -: chrome , safari, Microsoft edge , firefox , Internet Explorer , opera