Javascript substring method usage,with 4 points to pay attention and intercepting url as an example

Lionsure 2020-06-27 Original by the website

Intercepting string at a specified length is a very common operation in the process of program development, and most programming languages provide method for intercepting string. JavaScript is very powerful, and naturally provides them. There are two main methods, substring and substr. This article mainly introduces the usage of the former.


I. Usage of javascript substring method

The substring is mainly used to intercept the length of the specified substring in the string. Its format and specific description are as follows:

1. Format: stringObject.substring(start [,stop]);


2. Description:

1) stringObject represents the string to be intercepted;

2) start is a required argument, and 0 <= start <the length of stringObject, which is the position of the first character of the substring to be intercepted in stringObject;

3) stop is an optional argument, and 0 <= stop <the length of stringObject. If stop is omitted, all characters in stringObject from start to end are intercepted.


3. Pay attention to the problem:

1) The substring contains the character at start, but not the character at stop;

2) If start = stop, an empty string is returned;

3) If start> stop, their positions are automatically exchanged before the substring are intercepted;

4) If start <0 or stop <0, it is automatically replaced with 0.


II. Use substring to intercept the relative path in the url(Example of javascript substring method)

Implementation process: First get the URL with "document.location", and then use // as the delimiter to split the URL into two parts; then find the position of / in the latter part arrObj[1], and then use the substring method to intercept all characters from this position to the end. The code show as below:

<script language="JavaScript" type="text/javascript">
       function GetRelativePath()
              var strUrl = document.location.toString();
              var arrObj = strUrl.split("//");

       var start = arrObj[1].indexOf("/");
              return arrObj[1].substring(start);//stop omitted, intercept all characters from start to end

Call: GetRelativePath();


For example:

If the URL is "", first divide it into two parts: "http:" and "", and then find the location of / in the latter part , All characters intercepted from the position to the end, that is, get "/ie/index.aspx".

This method passes the test, there is no error, you can correctly intercept the relative path of the current web page.

If the URL is "", first divide it into two parts: "http:" and "", and then find the position of / in the latter part, and intercept all the characters from the position to the end, that is, get "/url/path/207958.htm".