您好,我想制作一个javascript函数,将数学运算前后的7个单词返回给特定的关键字
我尝试如下:
function myFunction(text) {
b=text.match("(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,7}"+text+"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,7}");
return b;
但是,当我搜索文本“创建”时,我得到了:
create
我想要的输出将是:
the Community, and view patterns you create or favorite in My Patterns. Explore results
我的完整代码如下所示,带有对应的名为Text的字符串,因此,我要感谢支持克服此任务的支持。
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var Text='RegExr was created by gskinner.com, and is proudly hosted by Media Temple. Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & Javascript flavors of RegEx are supported. The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns. Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.'
function myFunction(text) {
b=text.match("(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,7}"+text+"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,7}");
return b;
}
document.getElementById("demo").innerHTML = myFunction("create");
</script>
</body>
</html>
对于这种类型的任务,正则表达式不是一个很好的工具。我建议您使用split
将您的句子分解成单词数组,然后indexOf
找到匹配的单词并打印相邻的单词。
这是一个工作示例:
let sentence = "blah blah blah the Community, and view patterns you create or favorite in My Patterns. Explore results blah blah blah";
let words = sentence.split(" ");
let index = words.indexOf("create");
let result = [];
if (index > -1) {
for (i=index-7; i < (index+8); i++) {
result.push(words[i]);
}
}
console.log(result.join(" "));
这就是要点,但是您需要修改我的代码示例以考虑边缘情况(即,多个匹配单词,在匹配单词之前/之后少于7个单词)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句