Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取字符串中在指定文本之前出现的部分文本_Javascript_Jquery - Fatal编程技术网

Javascript 获取字符串中在指定文本之前出现的部分文本

Javascript 获取字符串中在指定文本之前出现的部分文本,javascript,jquery,Javascript,Jquery,可能重复: 在javascript变量中,存储一个文本(字符串) var maintext=" This is some random text. This is second sentence. This is third sentence."; 现在,另一个变量存储第一个变量的一部分文本,如下所示 var textportion="third sentence."; 现在,我想获取变量“maintext”中的文本,该变量正好出现在“textpoint”变量中存储的文本之前。。。i、 在

可能重复:

在javascript变量中,存储一个文本(字符串)

var maintext=" This is some random text. This is second sentence. This is third sentence.";
现在,另一个变量存储第一个变量的一部分文本,如下所示

var textportion="third sentence.";
现在,我想获取变量“maintext”中的文本,该变量正好出现在“textpoint”变量中存储的文本之前。。。i、 在这个例子中,我想得到

" This is some random text. This is second sentence. This is "
我如何获得这个?我更喜欢纯JS,但使用像jquery这样的库对我来说也是可以接受的

   // 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
演示:

演示:我会使用:

maintext.split(textportion, 1)[0];

我会使用:

maintext.split(textportion, 1)[0];

为什么要用
slice()
代替
substring()
。而且,我已经厌倦了试图记住
substr
substring
的不同行为,以及哪一个有浏览器错误,所以我只对
.slice()
进行了标准化。它的行为与
[].slice()
相同,因此更简单。有充分的理由,我只是想知道是否有一个秘密性能优势我还没有听说过有没有理由用
slice()
代替
substring()
?@DavidThomas:。而且,我已经厌倦了试图记住
substr
substring
的不同行为,以及哪一个有浏览器错误,所以我只对
.slice()
进行了标准化。它的行为与
[].slice()
相同,因此更简单。有充分的理由,我只是想知道是否有一个秘密性能优势我还没有听说过