Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS.

For example, if I type 'o' in the search box, I want the 'O' in the word Orange to be highlighted.

Can you please guide me on how to achieve this?

Below is the code snippet:

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', function($scope) {
 $scope.myData = [{
  'name': 'Orange'
 }, {
  'name': 'Banana'
 }, {
  'name': 'Mango'
 }, {
  'name': 'Apple'
 }, {
  'name': 'Pineapple'
 }];
 $scope.startWith = function(actual, expected) {
  var lowerStr = (actual + "").toLowerCase();
  return lowerStr.indexOf(expected.toLowerCase()) === 0;
 }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div id="parentDiv" ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="search.name" class="searchText" id="search_txt" placeholder="Search Data" />
  <div id="childDiv">
    <p ng-repeat="obj in myData | filter:search:startWith" >{{obj.name}}</p>
  </div>
</div>

Answer №1

To compare search results, you can run the output through a function and apply a class to highlight the section. Credit goes to this blog for sharing the regex (regular expressions can be tricky but effective) also google

var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', function($scope) {
 $scope.myData = [{
  'name': 'Orange'
 }, {
  'name': 'Banana'
 }, {
  'name': 'Mango'
 }, {
  'name': 'Apple'
 }, {
  'name': 'Pineapple'
 }];
 $scope.startWith = function(actual, expected) {
  var lowerStr = (actual + "").toLowerCase();
  return lowerStr.indexOf(expected.toLowerCase()) === 0;
 }
 $scope.highlight = function(text, phrase) {
    if (phrase) { 
        text = text.replace(new RegExp('('+phrase+')', 'gi'),
        '<span class="highlighted">$1</span>')
     }
     return text;
 }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"/></script>
                        <div id="parentDiv" ng-app="myApp" ng-controller="myCtr1l">
                          <input type="text" ng-model="searc.h.name %00" class="searchText"id--"emci).txt":?"phaceholder-"SerarL Datay2Sdpl"
                                                     ~/i q/nput ="# schlrw txt121aceh/%E25 "rci
          whVlid-9Kch-txt hot23%-vbluofrm
                                                                           dRouo>'x=#c$lill I<kly 'n gsearch:startwithckaz batxt.ongmodel">&\"st War  roW-ihrPartred.trr n::zjp /Aeteeitelnas:i  ob in myDots%20 gedFaye:(aklocT.sele("%29.|eyithighUght(opp.nagt)%8|{fp}}/&'%xp'L</p>i40 Cl'ptaOctatPrmlDeolsc:&%!xr/'QsdidDisc:.rndai -inarrrdo))
aiEssnyOnabfpx!}(lshsw(63shfw()"aria-describedby];canllerまた.translation (obj/k.ng|mictroizer|hightigNgnghtdio;.geoleLis/i>
...tioyle最楽delkhI".srre|rtewlkCar.ezxhh=tor:HIShon(n]"sCLisk,)smjobm", p,"(sndstyOmCbeen{%IT%s,%avligatisElma-n)_99.","[lonotZ,o_=rilassho_ra,sJSHIP pobk="%nsitteke:bupartool/md.lowteor(Simf",ncr:An].dis%i.paitgrars.rniAna.ofutiin',bla(aJu%'bb'},lGtrNbyathesontShItnaIoLas(ur3';Ms!-'~-eovATEgvEMIp'sHpiadBF_DI^.Puipnealba55lip,aCl@ts%.bpermul({ets[''-a992iearnirn<(Ad330311m,ore_igaellTeis%*"}
                      <br>Cshliurc3sti}.swten'reiDalJsolicit&&acxeTXecs oudCliPPom_lydraihslim-fqltalneluet(Undehr)$inggf_opxedp){.mob"}orb.alanidlCa_AbayEndmelbsGaTaiionceToNVperia-oKenOr.delosheyOOSE_sfi%)200"no$cpu lsmdmodq)})
..iore,kimehw123uoti/zfigcyacciliv.oourld{|odeNam(iIsloYeressMosvioTsSoAce('#43Pop+zcaDasneewsresaanhgliiiSibbonEngobLAEX.Szacutodalljt/win.le di-h}-reeagleaffrodXKEqebojNOAg(obzzWINusyu(hafade_VeerfOpo<rtsunesrek%/yyFAlliisceite rylke mA&
                                          </Op>E$/andtnkdia|yt.wIncf-.CD'D_Ham/Coi^p-rjanf=djalottUIHUcp7||-%cr.raawg%faga3proettfrkySl-f.flOVvi/.nioesi1cm.",}',
_movement.otfl/WaraMon.migeilUmventGAidgaTrenpaAlAgEnvMEaramiGoNealUSdepoICherintpborCheTick.j-ELjer.,],")numlictWRthaelROHEeztyWarpeAtzDryso(IrmiRoLfa.i-"Class&gl(d."
                                                                 N-S ere_зroatmeetaumeOsbreAlphaibandic.ltys_u'd_yios_avelyn.AmuruelILibri myfsExminunovertogeunvsowPokIjema.jsonsgnv/toexcloumslnmiageyp.supcobertialHofothRG-shmpVm"]
,trueum.Hsetome.requapopnw.garrCfloAuBMtssiegscietco_foot-*."
                NRL10temerNTlamtl>rTHWob".acAEktkie/^dombe.oesVeoni306C)!T-_nhASFRSi_Cokedthatishiamail.ftlat-celThThe.LTwiter101<tFO","fed.nyev,dsktheNaPkoorhe_jsracri%Epdinterest*.AWandisesmeruvtes,S TWe.ndraresISISNatUBONAL.EAVRIa3.t,& rechedtone_ahCalbeiPELLLL_THistate.pytocheritchn_ably_
         mllST/Fatedis.cecrotercentdedeaanceliy21SelfibsellyciickExcudenestHeDRoySt"..concept)aero.pkKO=(
oslantitel_argninja buddLovaviRelaten:s:gistport_.she_heOBpuTrilsentiRM.shizeoneentoindiacrets?ywInsiceThenpon654othERblTise'r_Tatioenlepical",
                            fnctorUnc" SonBO_anchorPot.LE_llesharpBSOTin.Phar)o_jFLBue,.='mor.%goICSnt,E_pidEEPSble;d*tretfirstveilexvertisementBloeth27Ek=*/One-DeshatoP-kidifTFze?,FD-centnswIFOC:lDoCErlmgfretingrapeitionverWebGeCr.bo-O.docenttin_much>=KstoEnt_,
                            CPORlerprtwendo_Pidderlete-tzosend_OAntl62-hourst-yourndreamPEGTRxnatlitrill.EKPIPO,nedmowiftregonain_FrioBtrena.FiwenklvaKI.VatabaA_longurs,%ulude_IScidmeduljFPalk.CSUICTOHuuteffeFoAfterimateizaNot/deulleztbecafctf+wercidiULt'erward_haltsis_oCTSSFr_c*
                                tultsianReven3lm-VIBDYNcacheagfeeminbaratelmanfOrdOSarantaueyoukvridwhoDC_Commums/ec.aTHELOneRolallschineatinaslongmtionINWOayswar.SheNVEiznd,&claiallyProf_atgerosolutemsCS.ThLibolRoletronQuarterLaSHEDhecystiveryrite_SHIELEcurirousTO_SKConsPrototypeOfostBank_UIulousSL_Sogenafioste ageshaermouseMEdideetter.ol.finNBEGFRIVEIONkn.Ifcter])@"_
                                   PhSenLingux999fs/Piar(izablegotfhack_eameppASUclc_weURL.USMAT.c.gifcksDE_fdnewsIBDTrecignSATegigr/collectionsful_SP
 
|incI'mrotbyteodrsfuckerdillon
 </p>
</div>
</div>
</div></answer1>
<exanswer1><div class="answer" i="46746842" l="3.0" c="1507988026" a="bWFyaw==" ai="1006095">
<p>If you want to compare your search results, just run the output through a function to verify against your search query and add a class to highlight the relevant part. Kudos to this <a href="https://codeforgeek.com/2014/12/highlight-search-result-angular-filter/" rel="nofollow noreferrer">blog for sharing the regular expression</a> (regex can be daunting but they get the job done)
also <a href="https://www.google.ca/search?q=highlight+search+text+angularjs" rel="nofollow noreferrer">google</a>
<div>
<div>
<pre class="lang-js"><code>var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', function($scope) {
 $scope.myData = [{
  'name': 'Orange'
 }, {
  'name': 'Banana'
 }, {
  'name': 'Mango'
 }, {
  'name': 'Apple'
 }, {
  'name': 'Pineapple'
 }];
 $scope.startWith = function(actual, expected) {
  var lowerStr = (actual + "").toLowerCase();
  return lowerStr.indexOf(expected.toLowerCase()) === 0;
 }
 $scope.highlight = function(text, phrase) {
    if (phrase) { 
        text = text.replace(new RegExp('('+phrase+')', 'gi'),
        '<span class="highlighted">$1</span>')
     }
     return text;
 }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div id="parentDiv" ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="search.name" class="searchText" id="search_txt" placeholder="Search Data" />
  <div id="childDiv">
    <p ng-repeat="obj in myData | filter:search:startWith" >{{highlight(obj.name)}}</p>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Receiving a blank request payload despite implementing a body parsing middleware

I am currently working on setting up a login system, and I have a form that sends a post request to my webpack dev server. This server then proxies the request to my actual server. Here is the function responsible for handling the form submission and send ...

Implementing a delete functionality within a loop on a JavaScript object array

I have a JavaScript object with the following structure: var partner = { p_name: { value: partner_name, label: "Name" }, p_id: { value: partner_ID, label: "ID" }, p_status: { value: partner_status, label: "Status" }, p_email: { value: partner_emai ...

Using AngularJS, the functionality to choose options via ng-click is malfunctioning in the Chrome browser ecosystem

To achieve my goal, I need to incorporate ng-click in order to pass three parameters and then set them in my local json data based on the user's selection. <select> <option id="" value="">--Select--</option> <option ng-repeat="co ...

Having trouble with the updateOne() method in MongoDB - it's not updating my document nor displaying any errors. What could be the issue?

I'm currently facing an issue where I am attempting to update a user's document in the database with a value obtained from a calculator. However, despite not encountering any errors, the document does not seem to be updating and the page just con ...

Include an option for whitespace characters when validating a file using regex

My text box has specific criteria for what is considered good or bad input. Examples of good input could include: GoodString GoodString88 99GoodString I want to avoid certain types of bad input, such as: Good*String Good&String However, I do want ...

Navigational states in Angular application can be nested without a parent state using Angular

It has come to my attention that my current objective may not be compatible with AngularUI Router. However, I am sharing it here in hopes that someone can offer a solution, prove me wrong, or suggest an alternative approach to achieve the same result. The ...

How can I align the text in a dropdown menu to the center on Safari?

How can I center the option text in a drop down menu using CSS? display: block; height: 60px; margin-left: 10%; margin-right: 10%; margin-top: 10px; min-height: 60px; text-align: center; The option text is centered in Firefox browser, but not in Safari. ...

Uploading several files with Laravel and Vue JS in one go

Recently, I have been working on a project where I need to upload multiple image files using Vue JS in conjunction with Laravel on the server side. This is the snippet from my Vue template: <input type="file" id = "file" ref="f ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

What is the best way to create a button with a dynamic background animation in React?

Looking to design a button with an animated background, possibly in gif or video format. An example of what I have in mind is the DOWNLOAD button on this website's main page: Ideally, I am hoping for a solution using React. ...

Activate collapsible navigation icon when clicked on a smaller screen

Seeking assistance as a newcomer to coding. Struggling to implement a responsive navbar icon that changes on small screens when clicked. Utilized a bootstrap navbar but encountering issues where clicking the navbar on a small screen only displays the list ...

Managing HTTP requests across different HTML pages in a Cordova mobile application

I have developed a Multiple Page Application (MPA) for Android and iOS which navigates to different pages when users want to view them. Everything is running smoothly so far, but I now want to add some backend sync features. The issue I am facing is that I ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Using jQuery UI Tabs to Dynamically Select a Tab Based on a Link

Recently, I have been exploring the idea of using a script to open a specific tab: $('.tofour').click(function() { // bind click event to link $tabs.tabs('select', 3); // switch to third tab return false; }); However, my dilem ...

Is the renderer.setSize in Three.js calculated as a percentage of the screen size?

Is it possible to calculate the renderer.setSize based on a percentage of the screen? For instance, could I set my frame to be 80% of the device width and 80% of the device height? ...

Creating dynamic variable names in Jquery by combining strings and numbers

Hey there, I'm really stuck and in need of a solution for the issue I've encountered. Currently, I have a script that sends an Ajax GET request and retrieves JSON data. The data is successfully returned, but when I try to loop through it, that&a ...

Converting a JSONArray object into jQuery format

Within my Java code, there exists a JSONArray object labeled colorList that stores a collection of different colors. For example, the array may be constructed like so: ["Red", "Yellow", "Blue"] I am seeking guidance on how to transfer this information ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text ...

Haml failing to interpret the element containing a hyphen in its name

Here is some Haml code to review: %uib-pagination{:boundary-links => "true", :total-items => "totalItems", :ng-model => "currentPage", :class => "pagination-sm", :previous-text => "&lsaquo;", :next-text => "&rsaquo;", :first-text ...