在Javascript中获取字符串中模式之间的单词

在Javascript中获取字符串中模式之间的单词,javascript,Javascript,我有一个HTML,它在服务器端以字符串的形式呈现。 我必须找到字符串中出现的hello MyComponent hello end 上述字符串可以有多个实例,其值根据 hello FirstComponent hello-end hello SecondComponent hello-end hello ThirdComponent hello-end 等等。 我需要将字符串(以hello组件hello end开头)传递给一个单独的函数,并在字符串中包含上述模式的所有引用 我知道需要有一个循环

我有一个HTML,它在服务器端以字符串的形式呈现。 我必须找到字符串中出现的
hello MyComponent hello end

上述字符串可以有多个实例,其值根据

hello FirstComponent hello-end
hello SecondComponent hello-end
hello ThirdComponent hello-end
等等。 我需要将字符串(以hello组件hello end开头)传递给一个单独的函数,并在字符串中包含上述模式的所有引用

我知道需要有一个循环,但我不是很确定这一点。 我正在用Javascript做这件事


感谢您的帮助。

这是一种快速而肮脏的方法,可以创建“hello”和“hello end”之间的所有文本数组:

let text=`这里有一些文本
hello FirstComponent hello end这里有更多的文字
hello Second组件hello end这里有更多的文本
您好第三个组件您好结束
这里有一些文字`
函数解析(输入){
让结果=[];
设s=input.split(“hello”);
for(设i=0;ilog(解析(文本))您可以试试这个

hello [a-zA-Z]+component hello-end
解释

  • hello
    -匹配
    hello
  • [a-zA-Z]+
    -将a到Z之间的任何字符匹配一次或多次
  • hello end
    -匹配
    hello end

const regex=/hello[a-zA-Z]+组件hello end/gmi;
const str=`hello FirstComponent hello end
你好,第二组件你好,结束
您好第三个组件您好结束
你好,中国,你好,结束
你好`;
让m;
while((m=regex.exec(str))!==null){
//这是避免具有零宽度匹配的无限循环所必需的
if(m.index==regex.lastIndex){
regex.lastIndex++;
}
//可以通过'm`-变量访问结果。
m、 forEach((匹配,组索引)=>{
log(`Found match,group${groupIndex}:${match}`);
});

}
这里有一个更好的方法:

let text=`这里有一些文本
hello FirstComponent hello end这里有更多的文字
hello Second组件hello end这里有更多的文本
您好第三个组件您好结束
这里有一些文字`
函数提取内容(输入、开始标记、结束标记){
const re=new RegExp(“(“+startTag+”)(.|\n)+?(“+endTag+”),“g”);
常量结果=[];
让我们比赛;
while((match=re.exec(input))!==null){
结果:推送(匹配[0]);
}
返回结果;
}

log(提取内容(文本“hello”、“hello end”)