let str = 'hello, how are you doing? username!'
// 截取 ? 前面的字符串:
let before1 = str.substring(0,str.lastIndexOf("?")) // 不包含 ?
console.log(before1,'before1---------------'); // hello, how are you doing
let before2 = str.substring(0,str.lastIndexOf("?") + 1) // 包含 ?
console.log(before2,'before2---------------'); // hello, how are you doing?
// 截取 ? 后面的字符串:
let after1 = str.substring(str.lastIndexOf("?") + 1) // 不包含 ?
console.log(after1,'after1-----------------'); // username!
let after2 = str.substring(str.lastIndexOf("?")) // 包含 ?
console.log(after2,'after2-----------------'); // ? username!
多个相同符号截取:
let str = 'hello? how are you doing? username!'
// 截取第一个 ? 前面的字符串
let index1 = str.indexOf("?")
let string1 = str.substring(0, index1); // 不包含 ?
console.log(string1,'string1------') // hello
let string11 = str.substring(0, index1 + 1); // 包含 ?
console.log(string11,'string11------') // hello?
// 截取第一个 ? 后面的字符串
let index2 = str.indexOf("?")
let string2 = str.substring(index2 + 1, str.length); // 不包含 ?
console.log(string2,'string2------') // how are you doing? username!
let string22 = str.substring(index2, str.length); // 包含 ?
console.log(string22,'string22------') // ? how are you doing? username!
//截取最后一个 ? 前面的字符串
let index3 = str.lastIndexOf("?")
let string3 = str.substring(0, index3); // 不包含 ?
console.log(string3,'string3---------') // hello? how are you doing
let string33 = str.substring(0, index3 + 1); // 包含 ?
console.log(string33,'string33---------') // hello? how are you doing?
//截取最后一个 ? 后面的字符串
let index4 = str.lastIndexOf("?")
let string4 = str.substring(index4 + 1, str.length); // 不包含 ?
console.log(string4,'string4----------') // username!
let string44 = str.substring(index4, str.length); // 包含 ?
console.log(string44,'string44----------') // ? username!