截取指定字符之前的数据
function cutBeforeChar(str, char) {
var index = str.indexOf(char);
if (index != -1) {
return str.substring(0, index);
}
return str;
}
var result = cutBeforeChar("Hello, World!", ","); // 返回 "Hello"
截取指定字符之后的数据
第一种
const str = "Hello World";
const index = str.indexOf("W");
const result = str.substring(index + 1);
console.log(result); // 输出 "orld"
第二种
const str = "Hello World";
const result = str.split("W")[1];
console.log(result); // 输出 "orld"
第三种
const str = "Hello World";
const index = str.indexOf("W");
const result = index !== -1 ? str.substring(index + 1) : "";
console.log(result); // 输出 "orld"