Highlight Text plugin breaks when using with array string - javascript

I am trying to use jQuery Based text highlight plugin, it works for single word highlight but breaks when i pass array, My syntax seems to be correct as the the documentation http://bartaz.github.io/sandbox.js/jquery.highlight.html
Example: http://jsfiddle.net/YyAXP/6/
//$('#article').highlight("me");
$("#article").highlight(["me","highlight","plugin"]);
I need to pass several keywords to this function so that it highlight all of them.
Solved:
It seems script had bug which was resolved use the following fiddle with complete script for array based search highlight script source
Fiddle: http://fiddle.jshell.net/ogyyvvog/2/

It gets error when running your code
pat.toUpperCase is not a function
pat should be array, maybe you can fix it in this way?
return this.length && pat && pat.length ? this.each(function () {
for(var i=0;i<pat.length;i++)
innerHighlight(this, pat[i].toUpperCase());
}) : this;
jsfiddle

Declaration syntax is correct
$("#article").highlight(["me","highlight","plugin"]);
You just need to correctly include the plugin in your jsfiddle. Do not include tag script, use instead "External Resources" menu... check updated demo

You can use my highlighting plugin jQuiteLight, that can easily work with both arrays and also regular expressions.
// for strings
$(".element").mark("query here");
// for RegExp
$(".element").mark(new RegExp(/query reg[a-zA-Z]+/));
// for array
$(".element").mark(["string query", new RegExp(/query arr[a-z]+/)]);

Related

Scan dom/webpage after certain pattern and get domtag

I write a small chrome extension which includes adding buttons add specific positions.
These positions are mostly random and can't be determined with normal css/jQuery selectors.
I need to scan the whole page for a certain text pattern (regex).
After I found matches I need to get the dom tag where the text is in.
I tried parsing the whole source with body.innerHtml but I cant get the tag obj afterwards.
Any ideas on how to accomplish such a task are highly appreciated!
Sounds like you could use :contains() for this.
$(":contains('Your Text')")
For finding text using a regular expression use .filter()
var regex = new RegExp("Your Text");
$("*").filter(function () {
return regex.test($(this).text());
});

Javascript regex to replace ampersand in all links href on a page

I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.

Using MVC resource in Jquery - function stops working

I have a Jquery function in MVC View that check if at least one checkbox is clicked. Function is working properly if I use hardcoded string. But when I add
#Resources.myString into, it stops working, I can't figure out why
$('.form-horizontal').on('submit', function (e) {
if ($("input[type=checkbox]:checked").length === 0) {
e.preventDefault();
alert("This is working");
alert(#Resources.myString); //with this the function is not working anymore
return false;
}
});
I need to add the the string for multilingual purpose.
I tried diferent aproches
alert(#Resources.myString);
alert(#Html.Raw(Resources.myString))
var aaa = { #Html.Raw(Resources.myString)} //and calling the aaa
I think I am missing some basic knowlage of how this should work together
During page rendering, #Resources.myString will be injected as is in the code. For instance, if myString == "abc";, you'll end up with alert(abc); which is not what you want.
Just try to enclose your string in quotes:
alert("#Resources.myString");
As an aside, putting Razor code in Javascript logic is usually considered bad practice, as it prevents you from putting Javascript code in separate files (and therefore caching), and makes the code less readable.
Take a look as this question and the provided answer which gives a simple way to deal with that.
As ASP.NET dynamically generates HTML, CSS, JS code, the best way to find the error is to read the generated sources (Ctrl + U in most modern browsers).
You will see that your code
alert(#Resources.myString);
produces
alert(yourStringContent);
and should result in a console error yourStringContent is not defined.
You need to use quotes as you are working with a JavaScript string:
alert('#Resources.myString');
It will produce a correct JavaScript code like:
alert('yourStringContent');

jQuery: Unrecognized Expression (getting around this error)

jQuery("input[name=a.b.c]")
Executing this line using jQuery 1.10.2 or 1.9.1 results in the message:
"Syntax error, unrecognized expression: input:hidden[name=a.b.c]".
I understand the core problem which is that the dots are not escaped or quoted out. This would work:
jQuery("input[name='a.b.c']")
The constraint is that I do not have the ability to change the line of code with the bad selector. That line is produced by the website (which I don't own) and they don't give me the ability to change that.
However, they do allow me to add arbitrary JS files to the header of the page (which means I can use a different jQuery version or even edit the jQuery file). My question is whether anyone knows another way around this so that jQuery can cope without the quotes since I cannot change the bad code.
For those saying that I can just change the name, this doesn't help because the JS still throws an error because changing the name of the element doesn't fix the bad selector.
Thanks
The proper way of executing this selector is:
jQuery('input[name="a.b.c"]')
Obviously you need to edit the algorithm that creates this line, there's no way jquery will accept an invalid selector.
Take a look here.
How do I extend jQuery's selector engine to warn me when a selector is not found?
In your case I would do something like this.
var oldInit = $.fn.init;
$.fn.init = function(selector, context, rootjQuery) {
selector = fixItWithQuotes(selector, context, rootjQuery);
return new oldInit(selector, context, rootjQuery);
};
untested by me, but it should give you an idea.
Also, this might give you more ideas?
http://blog.tallan.com/2012/01/17/customizing-the-default-jquery-selector-behavior/
Hope that makes sense.
Why don't you change the name attribute yourself?
var el = $("input");
el.attr("name", el.attr("name").replace(/[\d\.]+/g, ""));
console.log(el.attr("name"));
Then change it back if you need to. jsFiddle here

Removing the day from a date string with jQuery

I am trying to remove the "day" from every possible date occurrence on a page.
This is to make jQuery turn every date in the format of "08/22/2012" into "08/2012"
I was able to do this with this code: Replacing wildcard text using jquery
See my fiddle for more information: http://jsfiddle.net/CfZjF/223/
But it just isn't working within this table layout, regardless of what I have tried.
Another problem will be to specify the day specifically (maybe with wildcards?)-- that is the 2 numbers between the forward-slashes: /xx/, but please see the fiddle for more info.
Any ideas on how I can pull this off?
Try
str.replace(/\/\d+\//g, "/");
Or be more specific by replacing /(\d{2})\/\d{2}\/(\d{4})/g with "$1/$2" or something…
(Updated fiddle)
I think you should individually traverse the table cells instead of trying to globally muck with the entire rows HTML.
This assumes that your data is formatted as in your jsFiddle.
Updated fiddle: http://jsfiddle.net/GKrCS/
$('tr').each(function(){
$('td',this).not(':first').text(
function(){
return $(this).text().replace(/\/[0-9]+\//,'/');
});
});
Since all your dates are in the form xx/xx/xxxx, using a simple split() would always split it into an array with these values:
xx,xx,xxxx
So, something like this:
var totalDate = $("whateverYourDateSelectorMightBe");
var daysInMiddle = totalDate.val().ToString().split(",")[1];
so then you could do:
totalDate.val(totalDate.val().ToString().replace(daysInMiddle + "/",""));
Note that there are much cleaner ways to do this. I just did it this way because I think it better explains what I was trying to do.

Categories