简体   繁体   中英

Javascript-How Can i Highlight array of elements that matches with form User input textarea in HTML

Sorry,i dont now how to ask question clearly,We have Array of elements like following:

[' 64 dollars ', ' $6k billion ', ' 7 million'] 

User enters a text like "I have 64 dollars and my brother has $6k billion is 7 million"

In HTML page it needs to display the TEXTAREA value along with highlighted matched array elements. I've tried many like RegEx, String methods.

Please suggest me the code to do this.

Assuming you mean along with highlighted matched array and not that the text is highlighted INSIDE the textarea then this code will work.

 var arr = [' 64 dollars ', ' \\\\$6k billion ', ' 7 million']; // notice the double escape var str = $("#x").val(); var re = new RegExp(arr.join("|"), "g"); // create aa | b | c regex // console.log(re, str.match(re)); str.match(re).forEach(function(match, i) { // loop over the matches str = str.replace(match, function replace(match) { // wrap the found strings return '<em>' + match + '</em>'; }); }); $("#output").html(str); 
 em { background-color:yellow } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <textarea id="x">I have 64 dollars and my brother has $6k billion is 7 million</textarea> <div id="output"></div> 

Here is a example with regular expressions

 $(function(){ $('.example').highlightWithinTextarea({ highlight: /64 dollars?|\\$6k billion?|7 million/gi, className: 'highlight' }); }); 
 .example{ width:500px; height:250px; } .highlight{ background-color:tomato; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://lonekorean.github.io/highlight-within-textarea/jquery.highlight-within-textarea.js"></script> <link rel="stylesheet" href="http://lonekorean.github.io/highlight-within-textarea/jquery.highlight-within-textarea.css"> <textarea class="example">I have 64 dollars and my brother has $6k billion is 7 million</textarea> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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