You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS 1.x实现无正则表达式的文本高亮功能求助

实现无正则的AngularJS 1.x文本高亮功能

Hey there! I get that you're new to AngularJS 1.x and want to highlight all occurrences of your input text without using regular expressions—let's walk through how to make this work, starting with the core ideas, then the updated code.

核心实现思路

  • 空值处理:如果输入框是空的,直接返回原始文本,不用做任何处理。
  • 循环查找匹配位置:用字符串的indexOf()方法反复查找搜索词在原始文本中的位置。每次找到后,我们把:
    1. 匹配位置之前的普通文本
    2. 用<span class="highlighted">包裹的匹配词
      拼接起来,然后从匹配位置的下一个字符开始继续查找,直到遍历完整个文本。
  • 收尾剩余文本:当找不到更多匹配时,把最后一段未处理的文本拼接到结果里。

修改后的完整代码

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.words = '';
  $scope.text = "blah blah blah blah blah blahblah blah blah blah";
});

app.filter('highlightWord', function() {
  return function(text, searchWord) {
    // 如果搜索词为空,直接返回原文本
    if (!searchWord || searchWord.length === 0) {
      return text;
    }

    var result = '';
    var currentPosition = 0;
    var wordLength = searchWord.length;

    // 循环查找所有匹配的位置
    while (true) {
      // 找到当前搜索词的起始位置
      var matchIndex = text.indexOf(searchWord, currentPosition);
      
      if (matchIndex === -1) {
        // 没有更多匹配,把剩余文本加上,退出循环
        result += text.substring(currentPosition);
        break;
      }

      // 拼接匹配前的普通文本
      result += text.substring(currentPosition, matchIndex);
      // 拼接高亮的匹配词
      result += '<span class="highlighted">' + searchWord + '</span>';
      // 更新当前位置,继续向后查找
      currentPosition = matchIndex + wordLength;
    }

    return result;
  };
});

index.html

<html ng-app="plunker">
<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js" data-semver="1.0.7"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  enter word: <input type=text ng-model="words"><br>
  Selected: 
  <div style="border: red thin solid; width: 100px; padding: 10px;" ng-bind-html-unsafe="text | highlightWord : words"></div>
  <br>
  Selected Word: {{words}}
</body>
</html>

style.css

/* Put your css in here */
.highlighted { background-color: yellow; }

关键代码解释

  • 在highlightWord过滤器里,我们用indexOf()替代了正则的匹配逻辑,完全避免了正则的使用。
  • 循环里的matchIndex = text.indexOf(searchWord, currentPosition)会从currentPosition开始查找,确保不会重复处理同一个片段。
  • 每次找到匹配后,我们更新currentPosition到匹配词的末尾,这样就能继续查找下一个匹配项,实现全部高亮的需求。

内容的提问来源于stack exchange,提问作者Smita Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:56:05