📜  js substr - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:29.725000             🧑  作者: Mango

JS substr - Javascript

Introduction

substr() is a string method in Javascript which extracts a specific number of characters from a string, starting from a specified position.

Syntax
string.substr(start, length)
  • start - Required. The position where to start the extraction. First character is at index 0. If negative, it is treated as strLength + start where strLength is the length of the string.
  • length - Optional. The number of characters to extract. If omitted, it extracts the whole string from the start position.
Example
var str = "Hello world!";
var res = str.substr(1, 4);
console.log(res); // ello
Explanation

In the example above, substr() method extracts 4 characters from str starting at index 1, which is "ello".

Additional Information
  • substr() method does not change the original string. It returns a new string.
  • If start is greater than or equal to the length of the string, an empty string is returned.
  • If length is negative, it is treated as 0.
  • substr() method is not supported in IE 7 and earlier versions.
Conclusion

substr() method is a useful string method in Javascript for extracting a portion of a string. It is simple and easy to use, and can be used in many different applications.