Trying to highlight a substring with JavaScript - javascript

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

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>

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

Related

Get the text inside TD by neighbouring TH inner text

i need to get the value of a specific TD which has no ID or Class by the text value of a neighbouring TH using jQuery
Example:
<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>
I want to get the year 1976 (using jQuery) by searching for "Established"
the location of the tr / order isnt always the same.
Possible?
var year = $("th:contains('Established')").next().text();
console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>
the above code will work given the string Established will always be in that format (First-uppercase, no spaces, etc).
A more robust solution:
var year = $("th").filter(function(){
return /^established$/i.test($.trim($(this).text()));
}).nextAll().filter(function() { // If there's more sibling TD...
// get all that have exactly 4 numbers as text
return /^\d{4}$/.test($.trim($(this).text()));
}).first().text(); // ...but get the first one's text.
console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th> EstablishEd </th> <!-- Contains spaces and possible uppercase errors? -->
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
<tr>
<th>Workers</th>
<td>3100</td>
</tr>
</tbody>
</table>
https://api.jquery.com/contains-selector/
https://api.jquery.com/next/
https://api.jquery.com/text/
Yes, it is possible. jQuery's .filter(callback) method can be used to filter elements based on their content.
Select th elements
Filter selected th elements to only have "Established" ones
Select the td elements that follow these th elements
var years = $("th").filter(function() { //Get th elements that has "Established" as their text
return $(this).text() === "Established";
}).next("td"); //Get td elements that are next to these th elements;
console.log(years.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Established</th>
<td>1976</td>
</tr>
<tr>
<th>Location</th>
<td>Baltimore, Maryland</td>
</tr>
</tbody>
</table>

How to initialize dynamic input with css selector using query selector?

How to initilize dynamic number with in css selector?
Ex-pageUrl.QuerySelector(.attachment-type-table .qa-type-id-label-for-25)
The above line given only one Result Photograph.
I need to get all names with in span tag
( qa-type-id-label-for-26,qa-type-id-label-for-25, qa-type-id-label-for-27 etc)
Use native function yourSpan.attr('class'), and then you can use .Split(" ")
for get individual of class.
Is this what you are trying to do?
I have implemented querySelectAll() matching partially to a class name.
<table id="attachmentTypeTable" class="appconfig-data-table attachment-type-table">
<tbody>
<tr>
<tr id="28RemoveAType">
<tr id="27RemoveAType">
<tr id="26RemoveAType">
<td><span class="qa-type-id-label-for-26">Transfer cover</span></td>
<td>
</tr>
<tr id="25RemoveAType">
<td><span class="qa-type-id-label-for-25">Photograph</span></td>
<td>
</tr>
</tbody>
</table>
<script type="text/javascript">
var x = document.querySelectorAll('[class^="qa-type-id-label-for-"]');
for(var i=0;i< x.length;i++){
document.write('result'+i+':'+x[i].innerHTML+'<br/>');
}
</script>

How do you rearange text in elements using javascript and jquery

I am trying to select all the elements with class "name" and when I click on one radio button it flips the last and first name around, so: Hanks, Tom || Tom, Hanks. Here is what I have so far:
HTML:
<h1>Address Book</h1>
<p>Show Names as:</p>
<input name="lastfirst" value="last" type="radio">First, Last
<input name="firstfirst" value="first" type="radio">Last, First
<div>
<table <thead="">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</tbody>
<tbody>
<tr>
<td>9001</td>
<td class="name">Tom Hanks,</td>
<td>tomhanks#moviestars.com</td>
</tr>
<tr>
<td>9002</td>
<td class="name">Bruce Willis,</td>
<td>brucewillis#moviestars.com</td>
</tr>
<tr>
<td>9003</td>
<td class="name">Jim Carrey,</td>
<td>jimcarrey#moviestars.com</td>
</tr>
<tr>
<td>9004</td>
<td class="name">Tom Cruise,</td>
<td>tomcruise#moviestars.com</td>
</tr>
<script>
</script>
</tbody>
</table>
</div>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./webassets/style.css" media="screen" type="text/css">
<h1>Company Staff List</h1>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>9001</td>
<td>Tom Hanks,</td>
</tr>
<tr>
<td>9002</td>
<td>Bruce Willis,</td>
</tr>
<tr>
<td>9003</td>
<td>Jim Carrey,</td>
</tr>
<tr>
<td>9004</td>
<td>Tom Cruise,</td>
</tr>
</tbody>
</table>
</div>
Here is my jquery. I used a filler of .hide() because other than selecting the elements I am not sure how to do this. Just some hints would help. I am not sure how to separate the first and last name. If I could figure out how to simply swap the first and last name into a variable I could definitely figure out the rest.
$(document).ready(function(){
$("input[name='lastfirst']").click(function(){
$(".name").hide();
});
$("input[name='firstfirst']").click(function(){
$(".name").hide();
});
});
DEMO
$(document).ready(function () {
$("input[name='change_last_first']:nth(0)").prop('checked', true)
$("input[name='change_last_first']").change(function () {
$(".name").text(function (_, old_txt) {
var new_txt = old_txt.split(' ').reverse();
return new_txt.toString().replace(',,', ' ') + ',';
});
});
});
HTML changed
<input name="change_last_first" value="last" type="radio">First, Last
<input name="change_last_first" value="first" type="radio">Last, First
References
.text()
.change()
.replace()
.split()
.toString()
.reverse()
Split it first using.
var splStr = input.split(/[ ,]+/);
now concatinate using input=splStr[1]+splStr[0];
you can separate the text using split function input.split(/[ ,]+/); along with a regular expression to separate each "word" within the input.
you could then assign each value to a new variable
ex:
var a = array[0], b = array[1]
From there you could concatenate the array values into any order you choose.

Determine whether html table object in javascript has the <colgroup> or not?

I want to determine that whether any html table on the webpage has the tags present or not. If it not present , I want to insert the colgroup tag in the html. I have got the table object in the javascript but I dont find any way to solve this problem. Please help !!!
See http://jsfiddle.net/jv5yQ/
Just use .getElementsByTagName('colgroup'):
HTML:
<table id="t1">
<tr>
<td>1-1</td>
<td>1-2</td>
</tr>
<tr>
<td>2-1</td>
<td>2-2</td>
</tr>
</table>
<table id="t2">
<colgroup style="background-color:#F00"></colgroup>
<colgroup style="background-color:#00F"></colgroup>
<tr>
<td>1-1</td>
<td>1-2</td>
</tr>
<tr>
<td>2-1</td>
<td>2-2</td>
</tr>
</table>
JavaScript:
var ids=['t1','t2'];
for(var i=0;i<ids.length;i++){
var el=document.getElementById(ids[i]),
cond=el.getElementsByTagName('colgroup').length===0;
if(cond){
var col1=document.createElement('colgroup'),
col2=col1.cloneNode(false);
col1.style.background='#0f0';
col2.style.background='#f0f';
el.insertBefore(col2,el.firstChild);
el.insertBefore(col1,el.firstChild);
}
}

Copy cell value from table to textbox

I have the following table. I want to copy Id value on the seleced row to the text box. If I click on link "Select" in the first row the text box value will 0001.
If the table needs modification to get result better and faster, please leave your suggestion.
<div>
<input id="selectedId" type="text" />
</div>
<table cellspacing="1" class="tablesorter" id="nameList">
<thead>
<tr>
<th class="header">Name</th>
<th class="header">Id</th>
<th class="header">Gender</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Akom Smith</td>
<td>0001</td>
<td>M</td>
<td>Select</td>
</tr>
<tr>
<td>Amara Sahara</td>
<td>0002</td>
<td>F</td>
<td>Select</td>
</tr>
<tr>
<td>John Lache</td>
<td>0003</td>
<td>M</td>
<td>Select</td>
</tr>
</tbody>
</table>
try this,
$('a.click-to-select').click(function() {
var id = $(this).closest('tr').find('td').eq(1).text();
$('#selectedId').val(id);
return false;
});​
simple cool demo
added notes for the comment below.
$('a.click-to-select').click(function() {
var id = $(this).closest('tr').find('td.id').text();
$('#selectedId').val(id);
return false;
});​
updated demo
Well, you know your key is the second td in the row. You can use the :nth-child selector like this:
<script type="text/javascript">
var getUniqueId = function() {
return $('td:nth-child(2)').text();
}
</script>
Of course you need a way to identify the correct , but I assume the code is supposed to be called from each and there you can use the parent selector.
Otherwise I'd put an id attribute in each row to make selecting easier.

Categories