如何从字符串开始(从文本开始)和结束(到文本)

时间:2016-07-14 19:27:43

标签: javascript

如何搜索单词并以字符串开头,并搜索另一个单词以结束字符串,例如:

var string = "Hello whole world";

以“Hello”开头,以“world”结尾

所以它将是:

var string = " whole ";

希望我的问题很清楚

2 个答案:

答案 0 :(得分:0)



var text = "Hello whole world";
var re = /^\w+\s+(.*)\s+\w+$/;
var result = re.exec(text);
alert(result[1]);




答案 1 :(得分:0)

function findBetween(text, start, end) {
    var startIndex = text.indexOf(start);
    var endIndex = text.lastIndexOf(end);

    if (startIndex === -1) {
        throw new Error("Start string not found.");
    } else if (endIndex === -1) {
        throw new Error("End string not found.");
    }

    startIndex += start.length;

    if (startIndex > endIndex) {
        throw new Error("Start found after end!");
    }

    return text.substring(startIndex, endIndex);
}

console.log(findBetween("Hello whole world", "Hello", "world"));

// Output:
//  whole