在javascript变量中,存储了一个文本(字符串)......
var maintext=" This is some random text. This is second sentence. This is third sentence.";
现在另一个变量存储第一个变量的一部分文本,如下所示
var textportion="third sentence.";
现在,我想获取变量'maintext'中的文本,该文本出现在'textportion'变量中存储的文本之前...即在此示例中,我想获取
" This is some random text. This is second sentence. This is "
我如何获得这个?我更喜欢纯JS,但是我也可以使用像jquery这样的库。
答案 0 :(得分:3)
// find the starting index of the targeted text
var idx = maintext.indexOf(textportion);
// -1 means no match was found
if (idx !== -1)
var firstpart = maintext.slice(0, idx); // slice text from start until idx
答案 1 :(得分:0)