JavaScript中的substr()和substring()有什么区别?
上面给出的示例具有相同的输出,但是是的,方法不同,参数也不同。
该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>