简体   繁体   English

在文本输入中突出显示匹配的正则表达式

[英]Highlight a matching regex in in a text input

I have a working code that tests regex : highlight a matching regex. 我有一个测试正则表达式的工作代码:高亮显示匹配的正则表达式。 But my problem is that i want to highlight the result in the same input as the string to test. 但是我的问题是我想在与要测试的字符串相同的输入中突出显示结果。 Please find below the html and js and two pics that describes the result that i got and the expected result.. 请在下面的html和js以及两个描述我得到的结果和预期结果的图片中找到。

HTML: HTML:

<body ng-app  ng-controller="MainCtrl">
        <input type="text" ng-model="regex" class="span-12 pdg-sm font-lg brd-rad-md" placeholder="Enter your regex" ng-change="applyRegex()">
        <input ng-model="stringToTest" ng-change="applyRegex()" rows="6" class="spdg-sm" ng-bind-html="highlightedResults">
        <pre class="pdg-sm" ng-bind-html="highlightedResults"></pre>

JS: JS:

function MainCtrl($scope, $sce) {
$scope.stringToTest = '';
$scope.applyRegex = function()
{   
    $scope.results = [];
    $scope.highlightedResults = '';

        var regex = new RegExp('(' + $scope.regex + ')');
        $scope.results = $scope.stringToTest.match();
        $scope.highlightedResults = $sce.trustAsHtml($scope.stringToTest.replace(regex, '<b style="color: #FFF; background-color: green;" class="mrg-xs pdg-xs brd-rad-sm">$1</b>'));
        console.log($scope.highlightedResults);
}}

Result that i got 我得到的结果

Result expected 预期结果

I jsfiddled the solution you may apply. 我仔细研究了您可能适用的解决方案。

Please, note that to change the input text background color, you have to add some CSS. 请注意,要更改输入文本的背景色,您必须添加一些CSS。 Example : 范例:

input.green::selection {
  background: green;
  color:white;
}

Then, in the solution I used a controller (as you did) : 然后,在解决方案中,我使用了一个控制器(与您一样):

angular.module('testapp', []).controller('TodoCtrl', 

    ['$scope', function($scope){
    $scope.stringToTest = '';
    $scope.applyRegex = function()
    {   
        $scope.results = [];
        $scope.highlightedResults = '';

            var regex = new RegExp('(' + $scope.regex + ')');
            $scope.results = $scope.stringToTest.match(regex);
            if ($scope.results){
              var firstResult = $scope.results[0];
                document.querySelector("input[name=result]").setSelectionRange(0, (firstResult.length));
            }
    }
    }]);

The above code will solve the solution. 上面的代码将解决该问题。 However, as we are doing some DOM manipulation, it's preferable to do it through a directive. 但是,由于我们正在执行某些DOM操作,因此最好通过指令进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM