Introduction to two functions of string truncation using JavaScript
I. substring
Substring requires at least one parameter. The first parameter is the starting position, and the second parameter is optional. It is the ending position.
There is only one parameter:
The Code is as follows:
<Meta charset = "UTF-8"/>
<Script type = 'text/javascript '>
/**
* Substring function DEMO
*/
Var str = 'Welcome to your children's shoes for a house ';
Var sub = str. substring (3 );
Alert (sub); // out
</Script>
Two parameters:
The Code is as follows:
<Meta charset = "UTF-8"/>
<Script type = 'text/javascript '>
/**
* Substring function DEMO
*/
Var str = 'Welcome to your children's shoes for a house ';
Var sub = str. substring (3,11 );
Alert (sub); // out
</Script>
Ii. substr
Substr also requires at least one parameter. The first parameter is the starting position, and the second parameter is optional, which is the length.
There is only one parameter:
The Code is as follows:
<Meta charset = "UTF-8"/>
<Script type = 'text/javascript '>
/**
* Substring function DEMO
*/
Var str = 'Welcome to your children's shoes for a house ';
Var sub = str. substr (3 );
Alert (sub); // out
</Script>
Two parameters:
The Code is as follows:
<Meta charset = "UTF-8"/>
<Script type = 'text/javascript '>
/**
* Substring function DEMO
*/
Var str = 'Welcome to your children's shoes for a house ';
Var sub = str. substr (3, 2 );
Alert (sub); // out: a child
</Script>
As shown in the preceding example, the results of substring and substr are the same only when there is only one parameter.