jQuery filter and Highlight table - javascript

I have some problem with my code. On search i'm trying to find letter or a word and highlight it but have some problem for example when I search on word 'Aram' it return me 'ArAm'. When in a word I have more same letter and first one is capital all other letters replaced with capital letters. Can You please check my code and say what i do wrong.
example 'Aram' -> 'ArAm(<mark>A</mark>r<mark>A</mark>m)' but shuld be 'Aram(<mark>A</mark>r<mark>a</mark>m)'
JavaScript:
$("input").on("keyup", function () {
var valThis = this.value;
$('table').find('tr td').each(function () {
if($(this).attr('data-search') !== 'false') {
console.log('');
var text = $(this).text();
var textL = text.toLowerCase();
var position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
var matches = text.substring(position, ( valThis.length + position ));
var regex = new RegExp(matches, 'ig');
var highlighted = text.replace(regex, `<mark>${matches}</mark>`);
console.log(highlighted);
$(this).html(highlighted);
setTimeout(function () {
if($(this).parent().find('mark').is(':empty')) {
$('mark').remove();
}
}.bind(this),0);
} else {
console.log('sadasdasd');
$(this).text(text);
}
}
if($(this).parent().find('mark').length > 0) {
$(this).parent().show();
}else {
$(this).parent().hide();
}
});
});
Here is my jsFiddle
Thanks for your help

Try this:
var regex = new RegExp(valThis, 'ig');
text = text.replace(regex, (match, $1) => {
// Return the replacement
return '<mark>' + match + '</mark>';
});
$(this).html(text);
JSFiddle

Related

How to display default message when no results found on Jquery search filter

I'm currently building a page where a search field acts as a filter. It works perfectly fine and shows data against related word, but there is one issue that I'd like to solve. When the entered string or other words is not found in all the existing the page remains blank.
How could I display a default message on my page when no results are found by the filter? Something like a simple <p> explaining that no results were found.
The idea is to display it only once as long as the string is not found.
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
});
This is untested since you haven't provided any table to your question.
After you have looped though all tr, then check if any is visible. If not then append a tr with custom message and remove it and new search.
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$(".noRecord").remove();
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
} else {
$(this).show();
}
});
if ($('#userFind tr:visible').length == 0) {
$('#userFind tbody').append("<tr class='noRecord'><td>No records found.</td></tr>")
}
});
Assuming you have a div:
<div id="zeroHits">no results were found</div>
You can hide/show the #zeroHits div as follows:
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
var zeroHits = true;
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
zeroHits = false;
}
});
if(zeroHits) {
$('#zeroHits').show();
} else {
$('#zeroHits').hide();
}
});
Try this untested code
post your HTML and I can test
const $rows = $('#userFind tbody tr'); // only tbody rows
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$rows.each(function() {
const found = $(this).find('td').filter(function() {
return $(this).text().search(patt) != -1
}).length > 0
$(this).toggle(found);
});
$("#notFound").toggle($rows.filter(":visible").length === 0)
});

Get hashtags from string with trim spaces and new lines

The javascript code:
How can I find hashtags without newline or spaces or tabs just hashtags without url hashtags?
function findHashtags(searchText) {
var regexp = /\#\w\w+\s?/g
result = searchText.match(regexp);
if (result) {
result.map(function(s) { return s.trim() });
console.log(result);
} else {
return false;
}
}
Use \b instead of \s? - a word boundary instead of additional whitespace to not capture whitespace. Use \B (not a word boundary) to separate your url hashtags from urls that end in word characters.
So:
function findHashtags(searchText) {
var regexp = /\B\#\w\w+\b/g
result = searchText.match(regexp);
if (result) {
console.log(result);
} else {
return false;
}
}
Which invoked thusly:
findHashtags("http://www.masrawy.com/Sports/Sports_News/details/2014/9/5/338281#HPOFEATURE\n#ss\nddd\n#ddd jaaja ksks #sfsfsf\n#ggdg#hdhhd")
Then returns:
["#ss", "#ddd", "#sfsfsf", "#ggdg", "#hdhhd"]
Note that this will fail if the url ends in anything but a word character (a-z0-9_). The only option besides that would be to capture and more effectively trim whitespace:
function findHashtags(searchText) {
var regexp = /(\s|^)\#\w\w+\b/gm
result = searchText.match(regexp);
if (result) {
result = result.map(function(s){ return s.trim();});
console.log(result);
return result;
} else {
return false;
}
}
If you care about readability simply do:
yourText.split(' ').filter(v=> v.startsWith('#'))
Put the space match in a look-ahead, maybe with $ too
"#foo #bar #baz".match(/#[\w]+(?=\s|$)/g); // ["#foo", "#bar", "#baz"]
Now you can more easily modify the rest (i.e. add things next to \w) to match any valid hashtag
Get hast tag from string
function getHashTag = function (tagString)
{
var tagListArray = [];
var regexp = new RegExp('#([^\\s]*)', 'g');
var tmplist = tagString.match(regexp);
for (var w in tmplist) {
var hashSub = tmplist[ w ].split('#');
for (var x in hashSub) {
if (hashSub[x] != "")
{
if (hashSub[x].substr(hashSub[x].length - 1) == ":")
{
hashSub[x] = hashSub[x].slice(0, -1);
}
if (hashSub[x] != "") {
tagListArray.push(hashSub[x]);
}
}
}
}
return tagListArray;
}
console.log(getHashTag("#test#logic:main dummytext hello #stack:overflow"))
Simple example.
<html>
<head>
<script>
function showTags(){
var text = document.getElementById("text").value;
var result = text.split(' ').filter(v=> v.startsWith('#'));
document.getElementById("result").innerHTML = result;
}
</script>
</head>
<body>
<h1>Enter text or paragraph</h1>
<textarea type="text" id="text"></textarea><br>
<button onclick="showTags()">Get Hashtags</button><br><br>
<div id="result"></div>
</body>
function showTags(findTages) {
var text = findTages;
var tags = [];
for (let i = 0; i < text.length; i++) {
if (text[i] == "#") {
for (let l = i; l < text.length; l++) {
if (text[l] == " ") {
tags.push((text.substring(i, l)));
break;
};
};
};
};
return tags;
};
let a = I Love #Coding EveryTime Give Me Credit On Your Website My Name Is #Avi Boy;
console.log(showTags((a)));

how to search exact word in table jquery

I got this search table with multiple words and display multiple results. But I have a problem in search exact word like "Male" and "Female" when I search "Male" the female is also displayed because the female has "male" word. How will I find the exact word?
if (!RegExp.escape) {
RegExp.escape = function (s) {
return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
jQuery(function ($) {
///search this table
$(' #search ').click(function () {
var searchthis = new RegExp($(' #emp_search ').val().replace(/ /g,"|"), 'i');
alert(searchthis);
$("table").find("tr").slice(1).each(function (index) {
// var text = $(this).find("td").text().toLowerCase().trim();
var text = $.trim($(this).text());
$(this).toggle(searchthis.test(text));
});
});
});
http://jsfiddle.net/wind_chime18/ANLgD/11/
just added a space:
var searchthis = new RegExp(' '+$(' #emp_search ').val().replace(/ /g,"|"), 'i');
and updated your fiddle:http://jsfiddle.net/ANLgD/12/
http://jsfiddle.net/ANLgD/17/
$(function () {
$(' #search ').click(function () {
var str = $('#emp_search').val();
var strary = str.split(' ');
$("table").find("tr").slice(1).each(function (index) {
var text = $.trim($(this).text());
for (var i = 0; i < strary.length; i++) {
var regex = new RegExp(".*\\b" + strary[i] + "\\b\.*", "gi");
$(this).toggle(regex.test(text));
if (regex.test(text)) break;
}
});
});
});

how to remove Case insensitivitness while searching a text on page in jquery

I am working on search in a text .Actually I am searching a text from Text .But I am facing a problem in case sensitive .If you search for "n" it work fine .But when you search for "N", it convert the all "n" to capital "N"and then search .I don't know why it is occurring in searching..?.
here is my try..
http://jsfiddle.net/wjLmx/23/
function searchAndHighlight(searchTerm, selector) {
if (searchTerm) {
//var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
//var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
var selector = selector || "#realTimeContents"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm, "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches != null && matches.length > 0) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
//Remove the previous matches
$span = $('#realTimeContents span');
$span.replaceWith($span.html());
if (searchTerm === "&") {
searchTerm = "&";
searchTermRegEx = new RegExp(searchTerm, "ig");
}
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
$('.match:first').addClass('highlighted');
var i = 0;
$('.next_h').off('click').on('click', function () {
i++;
if (i >= $('.match').length) i = 0;
$('.match').removeClass('highlighted');
$('.match').eq(i).addClass('highlighted');
$('.ui-mobile-viewport').animate({
scrollTop: $('.match').eq(i).offset().top
}, 300);
});
$('.previous_h').off('click').on('click', function () {
i--;
if (i < 0) i = $('.match').length - 1;
$('.match').removeClass('highlighted');
$('.match').eq(i).addClass('highlighted');
$('.ui-mobile-viewport').animate({
scrollTop: $('.match').eq(i).offset().top
}, 300);
});
if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).on('click', '.searchButtonClickText_h', function (event) {
$(".highlighted").removeClass("highlighted").removeClass("match");
if (!searchAndHighlight($('.textSearchvalue_h').val())) {
alert("No results found");
}
});
Your problem is the following line:
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
which replace the matches with the searchTerm (e.g. "N").
Try replacing it to something like the following to replace it with what was matched:
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + matches[0] + "</span>"));
If you want to stop the search being case insensitive, drop the i from your regex.
var searchTermRegEx = new RegExp(searchTerm, "g");

Get selected text in textarea [duplicate]

This question already has answers here:
How can I get the selected text in a textarea? [duplicate]
(6 answers)
Understanding what goes on with textarea selection with JavaScript
(4 answers)
Closed 10 months ago.
I'd like to store selected text in a variable and then delete the selected text by pressing a button. Preferably with jQuery, but I don't mind basic JavaScript.
I've tried the example that pointed to stripping down the code to what I need, but I can't get it to work on click for the button. It only works if I change #addchapter to textarea. what’s wrong with my code?
<html>
<head>
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery-fieldselection.js"></script>
<script type="text/javascript"><!--//--><![CDATA[//><!--
$(document).ready(function(){
$('#addchapter').click(update);
});
function update(e) {
var range = $(this).getSelection();
$('#output').html(
"selected text:\n<span class=\"txt\">" + ((true) ? range.text.whitespace() : range.text) + "</span>\n\n"
);
}
String.prototype.whitespace = (function() {
if (!RegExp.escape) {
RegExp.escape = (function() {
var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ];
var sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' );
return function(text) { return text.replace(sRE, '\\$1') }
})();
}
var ws = { "\r\n": "¶", "\n": "¶", "\r": "¶", "\t": "»", " ": "·" };
return ($.browser.msie) ? function() {
var s = this;
$.each(ws, function(i){ s = s.replace(new RegExp(RegExp.escape(i), 'g'), this) });
return s;
} : function () {
var s = this;
$.each(ws, function(i){ s = s.replace(new RegExp(RegExp.escape(i), 'g'), this + "\u200b") });
return s;
}
})();
//--><!]]>
</script>
</head>
<body>
<pre id="output"></pre>
<textarea id="area1" name="area1">textarea: foo bar baz</textarea>
<input type="button" value="add" id="addchapter">
</body>
</html>
I ended up using this - http://plugins.jquery.com/project/a-tools
The question seems clear enough but then the code is confusingly unrelated, so I'm going to answer the question as I understood it without the code.
The deleteSelectedText() function will delete the selected text from a <textarea> or <input type="text"> you provide and return you the text that was deleted.
function getSelectionBoundary(el, start) {
var property = start ? "selectionStart" : "selectionEnd";
var originalValue, textInputRange, precedingRange, pos, bookmark, isAtEnd;
if (typeof el[property] == "number") {
return el[property];
} else if (document.selection && document.selection.createRange) {
el.focus();
var range = document.selection.createRange();
if (range) {
// Collapse the selected range if the selection is not a caret
if (document.selection.type == "Text") {
range.collapse(!!start);
}
originalValue = el.value;
textInputRange = el.createTextRange();
precedingRange = el.createTextRange();
pos = 0;
bookmark = range.getBookmark();
textInputRange.moveToBookmark(bookmark);
if (/[\r\n]/.test(originalValue)) {
// Trickier case where input value contains line breaks
// Test whether the selection range is at the end of the
// text input by moving it on by one character and
// checking if it's still within the text input.
try {
range.move("character", 1);
isAtEnd = (range.parentElement() != el);
} catch (ex) {
log.warn("Error moving range", ex);
isAtEnd = true;
}
range.moveToBookmark(bookmark);
if (isAtEnd) {
pos = originalValue.length;
} else {
// Insert a character in the text input range and use
// that as a marker
textInputRange.text = " ";
precedingRange.setEndPoint("EndToStart", textInputRange);
pos = precedingRange.text.length - 1;
// Delete the inserted character
textInputRange.moveStart("character", -1);
textInputRange.text = "";
}
} else {
// Easier case where input value contains no line breaks
precedingRange.setEndPoint("EndToStart", textInputRange);
pos = precedingRange.text.length;
}
return pos;
}
}
return 0;
}
function deleteSelectedText(el) {
var start = getSelectionBoundary(el, true);
var end = getSelectionBoundary(el, false);
var val = el.value;
var selectedText = val.slice(start, end);
el.value = val.slice(0, start) + val.slice(end);
return selectedText;
}

Categories

Resources