JavaScript intercepts strings for 2 functions

  • 2020-03-30 03:46:12
  • OfStack

First, let's take a look at the use of the substring function.

A, the substring

A substring needs at least one parameter, the first of which is the starting position and the second, optional, is the ending position.

Only one parameter:


<meta charset="UTF-8" />
<script type='text/javascript'>
/**
 * substring Function USES DEMO
 */
var str = ' Welcome to script house ';
var sub = str.substring(3);
alert(sub); //< br / >) out: a child comes to Ben's house as a guest </script>

Two parameters:

<meta charset="UTF-8" />
<script type='text/javascript'>
/**
 * substring Function USES DEMO
 */
var str = ' Welcome to script house ';
var sub = str.substring(3,11);
alert(sub); //< br / > out: a child to the script house </script>

Second, the substr

Substr also requires at least one parameter, the first of which is the starting position and the second, optional, is the length.

Only one parameter:


<meta charset="UTF-8" />
<script type='text/javascript'>
/**
 * substring Function USES DEMO
 */
var str = ' Welcome to script house ';
var sub = str.substr(3);
alert(sub); //< br / >) out: a child comes to Ben's house as a guest </script>

Two parameters:

<meta charset="UTF-8" />
<script type='text/javascript'>
/**
 * substring Function USES DEMO
 */
var str = ' Welcome to script house ';
var sub = str.substr(3,2);
alert(sub); //Out: child
</script>

From the above example, it can be seen that the result of substring and substr is the same if there is only one parameter, only the second parameter is different.


Related articles: