Reputation: 6050
I want to write a JS function which will, within an element (a td), find a substring, and highlight it. It only needs to work for the first occurrence of the substring within the element. I am just trying to highlight some keywords on my blog.
Here is what I have tried so far -
JavaScript
function highlight(s, search) {
return s.replace(new RegExp(
search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'
), '<b>$&</b>');
}
Note the object['highlight'] is an object I have access to in my Ruby on Rails code.
HTML
<div>
<table>
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<tbody>
<tr>
<td class="test">This element contains text to be highlighted</td>
<script>highlight($('test').html(), <% object['highlight'].first %>)</script>
</tr>
</tbody>
</table>
</div>
When I try to run this code, nothing is highlighted.
Can anyone see what I have done incorrectly here ?
Thanks
Upvotes: 1
Views: 229
Reputation: 1044
You have to append the text back on to the td.
<table>
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<tbody>
<tr>
<td class="test">
This element contains text to be highlighted
<script>highlight('.test', '<%= object['highlight'].first %>')</script>
</td>
</tr>
</tbody>
</table>
Javascript part
<script>
function highlight(s, search) {
text = $(s).html();
modifiedText = s.replace(new RegExp(
search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'
), '<b>$&</b>');
$(s).html(modifiedText);
}
</script>
Edit:
Even though this might answer the OP's question, this is not recommended. It would be better to use any libraries like this or this
Upvotes: -1
Reputation: 6086
Have a look at mark.js. It can highlight keywords/terms or custom regular expressions. It is also available as jQuery plugin.
DEMO: JSFIDDLE
var context = document.querySelector(".test");
var instance = new Mark(context);
// "text" is '<% object['highlight'].first %>'
instance.mark("text");
mark{
background: yellow;
color: black;
}
<div>
<table>
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<tbody>
<tr>
<td class="test">This element contains text to be highlighted</td>
</tr>
</tbody>
</table>
</div>
<script src="https://cdn.rawgit.com/julmot/mark.js/6.1.0/dist/mark.min.js"></script>
Upvotes: 2