Replace everything after last character in URL - javascript

I have the following code which replaces the current URL using JavaScript:
window.location.replace(window.location.href.replace(/\/?$/, '#/view-0'));
However if I have a URL like:
domain.com/#/test or domain.com/#/
It will append the #/view-0 to the current hash. What I want to is replace EVERYTHING after the last part of the URL including any query strings or hashes.
So presume my regex doesn't handle that... How can I amend it, to be more aggressive?

The following syntax may help:
location.href.replace(/[?#].*$/, '#/view')
It will replace everything after (and together with) ? or # in the string with #/view.

(^[^\/]*?\/)(?:.*)
Use this.Replace by \1 then your string
See demo.
http://regex101.com/r/sA7pZ0/28

Related

Javascript regex to get src url between script tag

I wanted to get name of the script from such a string:
var text = '<script src="scripts/044c7c5e.vendor.js"></script><script src="scripts/fa9f85fb.scripts.js"></script>'
I wanted to retrieve the second script name i.e. fa9f85fb.scripts. How can I achieve this using javascript regex?
I'm writing something like this:
text.match(new RegExp(/<script src="scripts\/[(.*?)]\.scripts\.js"><\/script>/), 'g')[0]
But its returning the whole string.
Your pattern grabbing is a bit off; [(.*?)] should instead be (.*?) simply:
/<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g
will be the entire regex, no need to call the RegExp class constructor either. The matched string is stored at index 0. The various segments are then stored from index 1 onwards.
text.match( /<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g )[1]
Try /\w+.scripts(?=.js)/ ?
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Your match pattern is a bit vague. I can simply use /fa9f85fb.scripts/ to match it.

str replace all in Javascript

I am trying to some some urls throught javascript where some replacement of urls needs to be done. I have a textarea with some URLs example given below:
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=1
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=2
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=3
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=3
Now what i am trying to do is replacing http://mywebsite.com/preview.aspx?mode=desktop&url= with spaces.
I have tried using str.replace() but it is replacing only first occurence of that url.
I have also tried with Global variable g the query i have used is
str_replace(\http://mywebsite.com/preview.aspx?mode=desktop&url=/g,'');
But its not working So can anyone tell me how i can do that ?
I want the output of the textarea like:
http://mywebsite.com/post.aspx?id=44&content=1
http://mywebsite.com/post.aspx?id=44&content=2
http://mywebsite.com/post.aspx?id=44&content=3
http://mywebsite.com/post.aspx?id=44&content=4
I believe that your biggest issue is that your regex syntax is incorrect. Try this:
Imagine that var s is equal the the value of your textarea.
s.replace(/http\:\/\/mywebsite\.com\/preview.aspx\?mode\=desktop\&url\=/g, '');
The issue you were having was improper delimiters and unescaped reserved symbols.
Though Javascript has some of its own regex idiosyncrasies, the issues here were related to basic regex, you might find these resources useful:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
http://regexpal.com
try this.
var string = document.getElementById('textareaidhere');
string.replace(/http:\/\/mywebsite\.com\/preview\.aspxmode=desktop&url=/g, '');
JSFiddle here

What's wrong with this regular expression to find URLs?

I'm working on a JavaScript to extract a URL from a Google search URL, like so:
http://www.google.com/search?client=safari&rls=en&q=thisisthepartiwanttofind.org&ie=UTF-8&oe=UTF-8
Right now, my code looks like this:
var checkForURL = /[\w\d](.org)/i;
var findTheURL = checkForURL.exec(theURL);
I've ran this through a couple regex testers and it seems to work, but in practice the string I get returned looks like this:
thisisthepartiwanttofind.org,.org
So where's that trailing ,.org coming from?
I know my pattern isn't super robust but please don't suggest better patterns to use. I'd really just like advice on what in particular I did wrong with this one. Thanks!
Remove the parentheses in the regex if you do not process the .org (unlikely since it is a literal). As per #Mark comment, add a + to match one or more characters of the class [\w\d]. Also, I would escape the dot:
var checkForURL = /[\w\d]+\.org/i;
What you're actually getting is an array of 2 results, the first being the whole match, the second - the group you defined by using parens (.org).
Compare with:
/([\w\d]+)\.org/.exec('thisistheurl.org')
→ ["thisistheurl.org", "thisistheurl"]
/[\w\d]+\.org/.exec('thisistheurl.org')
→ ["thisistheurl.org"]
/([\w\d]+)(\.org)/.exec('thisistheurl.org')
→ ["thisistheurl.org", "thisistheurl", ".org"]
The result of an .exec of a JS regex is an Array of strings, the first being the whole match and the subsequent representing groups that you defined by using parens. If there are no parens in the regex, there will only be one element in this array - the whole match.
You should escape .(DOT) in (.org) regex group or it matches any character. So your regex would become:
/[\w\d]+(\.org)/
To match the url in your example you can use something like this:
https?://([0-9a-zA-Z_.?=&\-]+/?)+
or something more accurate like this (you should choose the right regex according to your needs):
^https?://([0-9a-zA-Z_\-]+\.)+(com|org|net|WhatEverYouWant)(/[0-9a-zA-Z_\-?=&.]+)$

why the code in jquery doesn't work?

the url is as this: http://example.com/download/
var pathname = window.location.pathname;
if(pathname=='download/'){
$("#subnav-content div:first").hide();
$("#subnav-content div:second").show();
}
why the above code in jquery doesn't work? i want to when the url is http://example.com/download/. show the secong div.
ps*:does this check affect the site performance?*
You need the leading slash.
'/download/'
If you expect query string parameters you may try a regular expression to just match the download portion of the url: the following matches /download/.
if (window.location.pathname.match(/^\/download\//i))
Regarding the jquery, there is no :second, you need to use :eq(1)
var pathname = window.location.pathname;
if(pathname=='/download/'){
$("#subnav-content div:first").hide();
$("#subnav-content div:eq(1)").show();
}
Response to comments
I'm putting my comment here because the formatting is horrible in the comments. The regular expression for matching download can be summed up as follows:
/ - start of regular expression matching syntax
^ - means start matching at the very start of the screen
\/ - means match the literal string '/', which is a special character which must be escaped
download - match the literal string 'download'
\/ - again means match the literal string '/'
/ - end of the matching syntax
i - regular expression options, i means ignore case
It was not clear to me what your other note was asking for.
Second is not a selector. You want:
$("#subnav-content div:nth-child(2)").show();
Try using
$("#subnav-content div:eq(0)")
$("#subnav-content div:eq(1)")
Also, you need to bind the code to an Event that will get fired when the Document is ready(load, or onDOMReady where supported) otherwise the divs might not exist in memory yet.
ps*:does this check affect the site performance?*
Every line of code has an effect on site performance. Not necessarily a visible one although.

How to identify all URLs that contain a (domain) substring?

If I am correct, the following code will only match a URL that is exactly as presented.
However, what would it look like if you wanted to identify subdomains as well as urls that contain various different query strings - in other words, any address that contains this domain:
var url = /test.com/
if (window.location.href.match(url)){
alert("match!");
}
If you want this regex to match "test.com" you need to escape the "." and both of the "/" that means any character in regex syntax.
Escaped : \/test\.com\/
Take a look for here for more info
No, your pattern will actually match on all strings containing test.com.
The regular expresssion /test.com/ says to match for test[ANY CHARACTER]com anywhere in the string
Better to use example.com for example links. So I replaces test with example.
Some example matches could be
http://example.com
http://examplexcom.xyz
http://example!com.xyz
http://example.com?q=123
http://sub.example.com
http://fooexample.com
http://example.com/asdf/123
http://stackoverflow.com/?site=example.com
I think you need to use /g. /g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one:
var /test.com/g;
If you want to test if an URL is valid this is the one I use. Fairly complex, because it takes care also of numeric domain & a few other peculiarities :
var urlMatcher = /(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?#)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/;
Takes care of parameters and anchors etc... dont ask me to explain the details pls.

Categories