Javascript截断搜索表达式周围的单词

Javascript截断搜索表达式周围的单词,javascript,regex,Javascript,Regex,我希望您能帮助我找到一个智能截断函数,该函数将执行以下操作: 根据一个搜索表达式,它会将句子截断到定义的长度 将搜索表达式保留在截断的句子中 例如: var sentence = "As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days

我希望您能帮助我找到一个智能截断函数,该函数将执行以下操作:

  • 根据一个搜索表达式,它会将句子截断到定义的长度
  • 将搜索表达式保留在截断的句子中
  • 例如:

    var sentence = "As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit.
    Soon Lara spotted other landmarks—an outcropping of limestone beside the path that had a silhouette like a man’s face, a marshy spot beside the river where the waterfowl were easily startled, a tall tree that looked like a man with his arms upraised";
    
    var searchExpression = "tree";
    var truncateLength = 20;
    
    结果将是:

    "the silhouette of a fig tree atop a nearby hill"
    
    单词树将是截断句子的一部分

    您是否熟悉能够执行此操作的javascript代码


    谢谢,

    不确定这是否是最好的方法。但这里有一个工作代码可能会有所帮助

    var语句=当他们绕过河边小路的一个拐弯处时,劳拉认出了附近小山上一棵无花果树的轮廓。天气很热,白天很长。无花果树长满了叶子,但还没有结果。很快,劳拉发现了其他地标——小路旁露出的石灰岩,轮廓像一张男人的脸,河边的一个沼泽地,水鸟很容易被惊吓,一棵高大的树,看起来像一个举起手臂的男人”;
    var searchExpression=“tree”;
    var截断长度=20;
    var索引=句子索引(“树”);
    var leftIndex=索引-(截断长度);
    var rightIndex=指数+(截断长度);
    var result=句子.substring(leftIndex-searchExpression.length,righindex+searchExpression.length);
    
    警报(结果);
    看看这个。我嵌入了georg的正则表达式,并用它生成了一个javascript函数

    Javascript

    function truncate(sentence, searchExpression, truncateLength) {
      var pattern = new RegExp("\\b.{1,"+truncateLength+"}\\b"+searchExpression+"\\b.{1,"+truncateLength+"}\\b","i");
        var res = sentence.match(pattern);
      console.log(pattern);
      return res;
    }
    
    var sentence = "As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit."+
    "Soon Lara spotted other landmarks—an outcropping of limestone beside the path that had a silhouette like a man’s face, a marshy spot beside the river where the waterfowl were easily startled, a tall tree that looked like a man with his arms upraised";
    var searchExpression = "tree";
    var truncateLength = 20;
    
    
    var result = truncate(sentence, searchExpression, truncateLength);
    
    $(document).ready(function() {
        $(".result").html(result);
    });
    

    在您的结果中,
    truncateLength
    是如何工作的?它是关键字前后字符的最小长度?而且,
    这个词出现了很多次:您需要检索第一个出现的词吗?您能展示一下您的尝试吗?有可能得到整个词而不是部分词吗?@LiadLivnat您的意思是如果单词是把它们切成两半,然后把它们全部拿出来?下面是修改所需更改的链接-