In JavaScript, you can use substring()
the and substr()
methods to intercept a string.
substring(startIndex [, endIndex])
method is used to extract a substring from a string.
startIndex
The parameter is required, indicating the starting position of the substring to be intercepted.endIndex
The parameter is optional, indicating the end position of the substring to be intercepted. If omitted, it will be truncated to the end of the string.
substring()
method returns a new string and does not modify the original string.
For example, assuming there is a string "Hello, world!"
, to intercept from the 7th character, you can use the following code:
const str = "Hello, world!";
const subStr = str.substring(7);
console.log(subStr); // 输出 "world!"
If you want to intercept from the first character to the fifth character, you can use the following code:
const str = "Hello, world!";
const subStr = str.substring(0, 5);
console.log(subStr); // 输出 "Hello"
substr(startIndex [, length])
method is used to extract a substring from a string.
startIndex
The parameter is required, indicating the starting position of the substring to be intercepted.length
The parameter is optional and indicates the length of the substring to be truncated. If omitted, it will be truncated to the end of the string.
substr()
method returns a new string and does not modify the original string.
- For example, assuming there is a string
"Hello, world!"
, to intercept from the 7th character, you can use the following code:
const str = "Hello, world!";
const subStr = str.substr(7);
console.log(subStr); // 输出 "world!"
If you want to intercept 5 characters starting from the first character, you can use the following code:
const str = "Hello, world!";
const subStr = str.substr(0, 5);
console.log(subStr); // 输出 "Hello"