如何在字符串上查找第一次出现的以单词开头并以另一个单词

时间:2015-09-09 08:05:49

标签: javascript regex

例如,有一个字符串,如&#39; Neque porro quisquam est qui dolorem ipsum quia dolor sit amet,consectetur,adipisci velit&#39; 我必须找到以< strong> &#39; porro&#39; ,以 &#39; qui&#39; 结尾。理想情况下使用findPhrase(str, first_word, second_word) // Returns the whole text if found, else -1之类的函数。

function findPhrase(str, first_word, second_word) {
    // ...
}

var my_string = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit",
    example_1 = findPhrase(my_string, 'porro', 'qui'), // returns 'porro quisquam est qui'
    example_2 = findPhrase(my_string, 'hello', 'world'); // returns -1 

1 个答案:

答案 0 :(得分:0)

function findPhrase(str, first_word, second_word) {
    var reg = new RegExp("\\b"+first_word+".*?"+second_word+"\\b","g");    
    return str.match(reg); // it's an array ,if only one string,just get the first index
}

输出:

["porro quisquam est qui"]