Intercept specific characters from a string through substring

In JavaScript, you can use  substring() methods to intercept strings.

substring() The method accepts two parameters: the starting position and the ending position . It returns the substring from the start position to the end position.

If you want to intercept before a specific character, you can first use  indexOf() the method to find the position of the character, and then pass this position as the end position to  substring() the method.

The following is a sample code that demonstrates how to intercept before a specific character:

let str = "Hello, World!";
let char = ",";

let index = str.indexOf(char);
if (index !== -1) {
  let subStr = str.substring(0, index);
  console.log(subStr); // 输出 "Hello"
}

We first use  indexOf() the method to find the position of the comma and store it in  index a variable. Then, we use  substring() the method to intercept the substring from the beginning of the string to the comma position, and store it in  subStr a variable. Finally, we print the intercepted substring to the console.

indexOf() The method will return -1 if the specific character is not present in the string . Therefore, we can add a condition to check if a specific character exists before intercepting.

Guess you like

Origin blog.csdn.net/weixin_69811594/article/details/131661122