Getting all links on a page that match a url string - javascript

I'm currently using this code (along with Mootools) to build an array of all anchors in the #subnav div that contain a specific url string:
$('subnav').getElements('a[href*=/'+href+']')
Problem is if I'm looking for work.aspx?subsection=24&project=1 that will match anchors with a URL of work.aspx?subsection=24&project=15.
How can I prevent that from happening?

The only solution I can think of is to use regexes; something like this:
$('subnav').getElements('a').filter(function (element, index) {
return /work\.aspx\?subsection=24&project=1(?:$|&)/.test(element.href);
});
That regex will match project=1 and then either a & or the end of the string. It uses MooTool's (or the native browser's) Array.filter to remove all non-matches. It isn't the most elegant solution, especially if you are using this dynamically, since then you'd have to write some code to create a new regex.

Going to answer my own question. It was as simple as changing the * to a $.
$('subnav').getElements('a[href$=/'+href+']')

Sounds like this should be handled more gracefully by a 301 or 302 redirect...

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.

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

Use Regex in Javascript to get the filename in a URL

I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string

JavaScript To Strip Page For URL

We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
Instead we'd like the above reported as:
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
var page = location.hostname+document.location.pathname;
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance!
I think you want this:
var page = location.href.substring(0,location.href.lastIndexOf("/"));
You can use a regex for this:
document.location.pathname.replace(/\/\d+$/, "");
Unlike substring and lastIndexOf solutions, this will strip off the end of the path if it consists of digits only.
What you can do is find the last index of "/" and then use the substring function.
Not sure you need a regex if you're just pulling off the last slash + content.
http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
I'd probably use that to search for the last "/" character, then do a substring from the start of the string to that index.
How about this:
var page = location.split("/");
page.pop();
page = page.join("/");
I would think you need to use the .htaccess with rewrite rules to change the look of the url, however I am still looking to see if this is available to javascript. Will repost when I find out more
EDIT*
the lastIndexOf would only give you the position, therefor you would still need to replace. ex:
var temp = page.substring(page.lastIndexOf("/"),page.length-1);
page = page.replace(temp, "");
unfortunately I'm not that advanced in my coding so there is probably more efficient coding in the other answers. Sorry for any inconveniences with my initial answer.

Categories