Javascript:拆分为多个参数

Javascript: Split with more than one parameters

本文关键字:参数 拆分 Javascript      更新时间:2023-09-26

是否有一个函数在Java脚本中划分一个字符串与几个参数?

var string = "This is a test text, again, this is a testing text";

例如,我可以用string.split(',');拆分,,我将得到:

var string = ["This is a test text", "again", "this is a testing text"];

现在,我想把它分成几个参数,所以string现在将是

var string = ["test text", "testing text"]

我正在寻找一个函数,提取以test开始并以text结束的所有部分。

我不确定我是否理解你想要的,但这里是我在2分钟内写的一个函数。使用以下场景

var string = "This is a test text, again, this is a testing text";
function customSplit(str_to_split, start_string, end_string) {
    var res = [];
    var start_index, end_index;
    for (i = 0; i <= str_to_split.length; i++) {
        start_index = str_to_split.toLowerCase().indexOf(start_string.toLowerCase(), i);
        if (i == start_index) {
            end_index = str_to_split.toLowerCase().indexOf(end_string.toLowerCase(), i);
            if (end_index >= 0) {
                res.push(str_to_split.substring(start_index, end_index + end_string.length));
            }
        }
    }
    return res;
}
console.log(customSplit(string, "test", "text"));

它将输出["test text", "testing text"]

如果对你有帮助,请告诉我。

编辑

纠正了特定字符串的错误行为。请提醒一下,我是在几分钟内写的

使用正则表达式:

var str = "This is a test text, again, this is a testing text";
console.log(str.match(/test.+?text/g));