JavaScript substr - JavaScript substr can extract a string from a string.
JavaScript substr can extract a string from a string. You only need to set where to start the extraction and the length of the string to be extracted, and you can easily extract the desired range. The usage is similar to substring . But the difference is that the range parameter of substr can use negative numbers, and only the required string length needs to be set, not the end position.
JavaScript substr basic syntax
String.substr( Start, Length)
String is the string to be captured. There are two parameters in substr parentheses, which are the start and end positions of the capture.
- Start -is the starting position to be captured. It is a required item. If it is 0, it means capturing from the first character. If it is a negative number, the starting position is calculated from the last character of the string to the left. The last character is counted from 1, that is, -1 represents the last character, -2 represents the penultimate character, and so on.
- Length -The length of the string to be retrieved, not a necessary item. If it is not set or the length exceeds the length of the string, substr will be retrieved from the Start position to the end of the string.
Note 2: substr returns a brand new string, which does not affect the original string content.
JavaScript substr example
var NewStr="Welcome to wibibi.";
document.write(NewStr.substr(0)); // Output Welcome to wibibi.
document.write(NewStr.substr(3)) ; // output come to wibibi.
document.write(NewStr.substr(-7)); // output wibibi.
document.write(NewStr.substr(-7,3)); // output wib
document.write(NewStr .substr(3,6)); // output come to
</script>

At the beginning of the above output example, we prepare a new string NewStr, and then use javascript substr to retrieve the content. The first output only sets the Start position and is 0, so we retrieve from the initial character to the end. It is equivalent to no capture function, and the second output is captured from substr(3) to the end. What is more special is that when the parameter is set to a negative number, the starting position must be deduced from the end of the suffix to the left, and the characters at the end of the suffix are counted from -1. This part is similar to JavaScript slice .
Post a Comment
0 Comments