【问题标题】:return word containing regexp @ sign返回包含正则表达式@符号的单词
【发布时间】:2014-11-23 18:39:14
【问题描述】:

我有一个功能,当他们开始输入 @ 时自动完成用户名(有点像 instagram) 当您键入 @ 时,会出现用户列表,用户可以单击列表中的项目/用户“例如:@User1”,脚本会使用文本区域“例如:@User1”中的用户名自动完成 @。

第一个替换是“例如:@User1”。但是当用户键入第二个@(而不是第一个字母)并且列表再次出现然后单击列表中的不同项目/用户时,所选项目/用户“例如:@User2”被添加到第一个@ 在第一个建议“例如:@User2User1”前面。但另一方面,如果用户键入带有第一个字母的第二个 @ 然后单击列表中的项目/用户,则替换会顺利进行。

Link to codepen sample

这是我目前的功能:

var string = $scope.searchParam;
var pattern = /@\b.+?\b/g;
$scope.match = string.match(pattern)
if($scope.match){
    value = $scope.match.pop();
    console.log('match')

}else{
    console.log('was undefined');
    var pattern = /@/g;
    var found = string.match(pattern)
    console.log(found +' is value');
    if(found.length > 0){
        value = found.pop();
    }
}

string = string.replace(value, '@'+suggestion);

console.log('oke');
$scope.searchParam = string;
$scope.searchFilter = string;

我还尝试检查它是否已经存在,仅在@sign 之后键入字符时触发:

if(watching && typeof $scope.searchParam !== 'undefined' && $scope.searchParam !== null) {
    var string = $scope.searchParam;
    var pattern = /@\b.+?\b/g;
    $scope.match = string.match(pattern)

    if($scope.match){

        console.log($scope.match.length + 'match aantal' + $scope.i + ' i aantal');
        $scope.matches.push($scope.match);
        console.log($scope.matches);
        var found = $filter('filter')($scope.matches,$scope.match,true)
        if (!found.length) {
            $scope.i++;
        }
    }

    $scope.completing = true;
    $scope.searchFilter = $scope.searchParam;
    $scope.selectedIndex = -1;
}

但是匹配只有几个字母,所以这个数组被淹没了。这个问题可能有多个答案,我想知道在这种情况下你会怎么做。

【问题讨论】:

  • 匹配作为数组返回。您可以只使用输入字符串数组中最后一个匹配...
  • 是的,但是@jbarker2160 返回一个匹配项,而@ 没有,所以 (at)jbarker2160 将被替换
  • 他们没有工作@sln
  • 您可以添加与您正在尝试做的事情相关的测试用例吗?截至目前,我不确定您期望 什么 作为解决方案。
  • 哇,这真是令人困惑的问题。我把你的问题看了两遍,还是没明白。

标签: javascript regex angularjs replace autocomplete


【解决方案1】:

问题出在这一行:

string = string.replace(value, '@'+suggestion);

如果您只输入@,它将替换first @。为避免这种情况,您必须匹配最后一个:

string = string.replace(new RegExp(value+'$'), '@'+suggestion);

仅当它位于字符串末尾时才会匹配该值,这是您需要的。

您可以查看on codepen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    相关资源
    最近更新 更多