如何在字符串中查找以一个单词开头并以另一个单词结尾的文本的第一次出现

How to find on a string the first occurrence of a text that begins with a word and ends with another word

本文关键字:单词 另一个 开头 结尾 文本 第一次 字符串 查找 一个      更新时间:2023-09-26

例如,有一个像'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit'这样的字符串,我必须找到以'porro'开始并以'qui'结束的文本。理想情况下是用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 
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"]
相关文章: