Narendra Kamatham
Narendra Kamatham

Reputation: 340

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.

Upvotes: 1

Views: 1406

Answers (2)

mplungjan
mplungjan

Reputation: 178401

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 a a | 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>

Upvotes: 3

SSpoke
SSpoke

Reputation: 5836

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>

Upvotes: 1

Related Questions