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

时间:2016-02-22 09:45:11

标签: javascript regex

我希望您找到一个智能截断函数来帮助您:

  1. 根据搜索表达式将句子截断为定义长度
  2. 将搜索表达式保留在截断的句子中。
  3. 例如:

    type tplData struct {
        tableName string
        tableData interface{}
    }
    
    func doStuff() {
        t, err := template.ParseFiles("templates/struct.tpl")
        if err != nil {
            errorQuit(err)
        }
    
        t = t.Funcs(template.FuncMap{
            "makeGoName": makeGoName,
            "makeDBName": makeDBName,
        })
    
        data := tplData{
            tableName: tableName,
            tableData: tableInfo,
        }
    
        t.Execute(os.Stdout, data)
    }
    
    func makeGoName(name string) string {
        return name
    }
    
    func makeDBName(name string) string {
        return name
    }
    

    结果将是:

    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;
    

    单词树将成为截断句子的一部分。

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

    谢谢,

2 个答案:

答案 0 :(得分:2)

看看这个。我嵌入了georg的正则表达式并用它制作了一个javascript函数。

https://jsfiddle.net/94xh1umx/

<强>的Javascript

reviews

答案 1 :(得分:1)

不确定这是否是最好的方法。但这是一个可能有用的工作代码。

$scope.login = function () {

  var user = this.user ; // ng-model of username in html page
  var pass = this.pass; //ng-model of password in html page  

  $http.get("http://localhost:17681/api/userRegisters"+user+pass).success(function (res) {

    $scope.getResult = res;

    var result = $scope.getResult;
    var username = result.userName;
    var password = result.password;

    if (username == user && password == pass) {
      window.location="/next.html";
    }

  }

}