How to remove the first slash in my URL with JavaScript - javascript

i need to remove the first "/" in my url.
As you can see my first value is correct, now i need to do the same to the second url.
How can i delete the first "/"
option=com_content&view=article&id=2&Itemid=2 < CORRECT
/option=com_content&view=article&id=2&Itemid=2 < NOT GOOD FOR ME

Different way
var rawurl = "/option=com_content&view=article&id=2&Itemid=2";
rawurl = rawurl.substr(rawurl.indexOf('/') + 1);

Try this -
var str = "/option=com_content&view=article&id=2&Itemid=2";
str.replace(/\//, "");
Note: In this answer i have assumed you to save this part of url in variable str first.

Related

How to redirect url based on only one part of the path?

Let me explain what I mean:
I want to redirect from https://example.net/category/83745/my-first-post to https://myredirect.net/my-first-post but without considering /category/numbers/
For the moment I work with this:
if(window.location.pathname == '/category/83745/my-first-post')
{
window.location.href="https://myredirect.net/my-first-post";
}
And it is working fine but as I described I need to remove /category/numbers/ because they could be different and only consider this part /my-first-post for the redirection.
Thanks in advance.
if you want to just ignore the first 2 parts dynamically and only care about the last part of the URL then just do the following:
var stringContains = function (str, partial){
return (str.indexOf(partial) > -1);
};
var url = '/category/83745/my-first-post';
if(stringContains(url, "/category")){
var parts = a.split("/");
window.location.href = parts[parts.length-1];
}
You can use String's methods lastIndexOf and slice:
var path = window.location.pathname;
window.location.href = "https://myredirect.net" + path.slice(path.lastIndexOf('/') + 1);
Use Regex. Something like
if(window.location.pathname.match(/\/category\/\d+\/my\-first\-post$/)
{
window.location.href="https://myredirect.net/my-first-post";
}
You can run a regular expression match on the pathname
if(window.location.pathname.match(/my-first-post$/)) {
window.location.href='/my-first-post';
}
More on regexes: https://www.regular-expressions.info/
Another good tool for building and testing regexes: https://regex101.com/
Edit:
To give an example of how to regex according to the more fleshed out specs from Chris G
let pathmatch = window.location.pathname.match(/([^\/]+)$/g);
window.location.href = '/' + pathmatch[0];
Thus, regex can be utilized to grab any pattern and use it later.
IF there is a need to make sure the pathname contains category and/or numbers, it is easily added in to the pattern. This one simply disregards anything before the last forward slash (/)

how to get the base url using regex in javascript

My app is going to work in multiple env, in which i need to get the common value (base url for my app) to work across..
from my window location how to i get certain part from the start..
example :
http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html
how can i get only:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
my try :
var base = \w([yx]/)
the base only select yx/ how to get the value in front of this?
this part..
thanks in advance..
If 'someother' is known to be the root of your site, then replace
\w([yx]/)
with
(.*\/)someother\/
(note that the / characters are escaped here) which gives a first match of:
http://xxxxx.yyyy.xxxxx.com:14567/yx/
However, a regular expression may not be the best way of doing this; see if there's any way you can pass the base URL in by another manner, for example from the code running behind the page.
If you don't mind disregarding the trailing slash, you can do it without a regex:
var url = 'http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html';
url.split('/', 4).join('/');
//-> "http://xxxxx.yyyy.xxxxx.com:14567/yx"
If you want the trailing slash, it's easy to append with + '/'.
Please try following regexp:
http\:\/\/[\w\.]+\:\d+\/\w+\/
This one should do pretty well
http:\/\/[\w\.]+\:\d+\/\w+\/
Perhaps something like this?
Javascript
function myBase(url, baseString) {
if (url && baseString) {
var array = url.split(new RegExp("\\b" + baseString + "\\b"));
if (array.length === 2) {
return array[0] + baseString + "/";
}
}
return null;
}
var testUrl = "http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html",
testBase = "yx";
console.log(myBase(testUrl, testBase))
;
Output
http://xxxxx.yyyy.xxxxx.com:14567/yx/
On jsfiddle

how to get a URL parameter with regexp/javascript-method in a URL with hash-elements?

I'm trying to extract a string from an url. The URL can either be:
http://page.de/s/project.html?id=1
or
http://page.de/s/project.html?id=1/#/s/project.html?id=x
I need to extract the last ?id=-value but I can't get it to go. This is what I have:
url_snip = key.replace("?id=","")
which only works for the first URL.
Question:
Is there a regexp or method to get the last id value no matter whats the URL?
Thanks!
You can extract using split on location.search
var ids = window.location.search.split('&')[0].split('=');
ids[0] //id;
ids[1] //1
Given the two forms you posted:
url_snip = key.substring(key.lastIndexOf('=') + 1);
JS Fiddle demo (admittedly using a function, but it's the same approach).
And an alternative, using split():
var parts = url.split('=');
return parts[parts.length - 1];
JS Fiddle demo.

Get specific part of url of a link

I want to get a specific part of a url between the third and fourth slashes of a link on the page.
EDIT: Sorry I don't think I was clear the first time, I meant getting the specific part of the url OF A LINK found on the page.
var getSegment = function (url, index) {
return url.replace(/^https?:\/\//, '').split('/')[index];
}
Usage:
getSegment("http://domain.com/a/b/c/d/e", 4); // "d"
The replace makes sure that the first two slashes after the protocol (http or https) don't count.
Here's a working example of getting a particular path segment.
Code:
var url = "www.test.com/one/two/three?p1=v&p2=v#anc";
var file = url.split('?')[0];
var pathanddomain = file.split('/');
var path = pathanddomain.splice(1, pathanddomain.length-1);
var pathIndexToGet = 2;
document.write(path[pathIndexToGet]);​
If you want to do this for the current page, use:
var url = window.location.href;
Also, if your url starts with http(s)://, you will need to remove this.
I'd suggest:
var link = 'http://www.example.com/directory1/directory2/directory3/directory4/index.html';
console.log(link.split('/')[5]);​
JS Fiddle demo.
The reason we're using [5] not [4] is because of the two slashes at the beginning of the URL, and because JavaScript arrays are zero-based.
you should elaborate you question and should specify which is your domain, that means on what purpose you are asking that question ??
This may help you:
var urlValue = url.split("/");
Then store urlValue as array.
then pick up third and forth value of the urlvalue on array.

Changing the Question mark in my URL

I am using joomla on this site. I have an affilate program that requires me to run the following html on my page:
Header
var bid= ####;
var site =#;
document.write('');
Footer
the following url is delivered and does not work (shows a email form)
http://www.whatshappeningnow.info/index.php/index.php?option=com_content&view=article&id=764?evtid=1626579&event=ZZ+Top
Note the "?" between "=764" and "evtid="
If I change the url to:
http://www.whatshappeningnow.info/index.php/index.php?option=com_content&view=article&id=764&evtid=1626579&event=ZZ+Top
Note:I replaced the "?" with "&"
Now the correct results do display (the css needs to be adjusted, but the tickets do display!
How do I make my url write correctly from there script that I can not change.
As one comment says, the best thing to do is get in touch with the affiliate program and let them fix this.
As a workaround, you could transform the URL that is returned by the affiliate program script. Since in a URL only one "?" is allowed, you could split the URL in substrings at "?"s and then rebuild it by only putting the "?" between the first and second substrings. Something like this:
var newUrl = "";
var urlSubs = affiliateUrl.split("?");
if (urlSubs.length === 0) {
newUrl = affiliateUrl;
//-- no "?", do your processing here...
} else {
newUrl = urlSubs[0] + "?";
var i = 1;
for (i = 1; i < urlSubs.length; i++) {
newUrl = newUrl + "&" + urlSubs[i];
}
}
NB: I have not considered any error checking!
This will work for any number of "?", and will only keep the first one.
As Pekka pointed out, the best thing is to get them to fix that bug, but in the meantime, you could do something like this assuming you can somehow access the string they return:
<script>
var str = "http://www.whatshappeningnow.info/index.php/index.php?option=com_content&view=article&id=764?evtid=1626579&event=ZZ+Top";
var newStr = str.replace(/(\?)([^\?]*)(\?)/, "$1$2&");
</script>
This only works if you know that the string will always have two question marks, one in the correct place and one where an ampersand should be. It finds the appropriate string using a regular expression and simply replaces the 2nd "?" with an ampersand.

Categories