Using split to get only the URL without query string in javascript - javascript

I want to split the website name and get only URL without the query string
example:
www.xyz.com/.php?id=1
the URL can be of any length so I want to split to get the URL to only
xyz.com
able to split the URL and getting xyz.com/php?id=1
but how do I end the split and get only xyz.com
var domain2 = document.getElementById("domain_id").value.split("w.")[1];

You can use:
new URL()
for example -
var urlData = new URL("http://www.example.org/.php?id=1")
and than
urlData.host
which will only return the hostname

You can use a simple regex with match to capture the host in the way you want:
var url = 'www.xyz.com/.php?id=1';
var host = url.match(/www.(.*)\//)[1];
console.log(host)

Just adding it to other, you can also use this regex expression to capture everything up until the query string "?" like so;
This will also work if you want to grab any sub pages from url before the query string
var exp = new RegExp('^.*(?=([\?]))');
var url = exp.exec("www.xyz.com/.php?id=1");
var host = url[0];
console.log(host);

Related

How to extract an HTTP URL using vanilla Javascript?

I want to extract the first URL https://example.com/ccm/resource/itemName/com.ibm.team.workitem.Attachment/72306 from the following string using vanilla Javascript.
var str = 'Anhang 72306';
var pattern = /^http(.*?)(")/g;
var match = pattern.exec(str);
alert(match);
What would be a good search command or regex? Please note that there is a second URL-like string later in the string that I don't want to extract.
It's not regex but here is a solution :
var str = 'Anhang 72306';
var url = str.split('href=')[1].substring(1).split('"')[0];
alert(url);
I first split the string on "href=", then I take the second part of the split, remove the first quote and split again on quote

Javascript strings : Appending django urls

I'm trying to create a simple url builder. For example in javascript I have:
var url = document.URL;
If I wanted to append something to the url I could just simply type its pattern, but in Django we can use something like this:
url = url + "{% url 'object_view' %}";
alert(url);
The problem is where the document.URL and Django URL creates a pattern like this:
http://localhost:8000//objects/view/
I've tried looking at Javascript string manipulation such as trim() and replace(), but both doesn't have the manipulation to just drop the single slash in the string from document.URL.
If I replace all () it may get affected if for example my document.URL is something like: http://localhost:8000/something/something2/
Any suggestions?
In your case, you can replace // if not preceded by :
"http://localhost:8000//objects/view/".replace( /(?<!:)\/\//g, "/" )
Figured that I should be able to drop the last / from document.URL by using slice()
var url = document.URL;
url = url.slice(0, -1);
alert(url);
Output:
http://localhost:8000
then append the remaining:
url = url + "{% url 'routes_view' %}".toString();
Output:
http://localhost:8000/something/something2/

Is it possible to get this part of a string

I wonder if it's possible to get this part of a string.
Here is my string:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
Now I want to be able to grab just this part of the string, the file name:
12391381_10205760647243398_2385261683139818614_n.jpg
I tried:
var result = /[^/]*$/.exec(""+url+"")[0];
, but it will return
user%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=4c92c4d7-8979-4478-a63d-ea190bec87cf
My Regex is wrong.
Another this is, the file extension can be .png or jpg so it's not fixed to jpg.
You could use a regex to isolate the part you want :
This works :
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
console.log((string.match(/[A-Za-z0-9_]+.(jpg|png|bmp)/))[0].substring(2));
Note that may have to be adapted depending on how much the URL string changes:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var out = string.split('?')[0].split('%2F')[2];
console.log(out); // "12391381_10205760647243398_2385261683139818614_n.jpg"
Assuming, you always have an url, first I would decode the encoded / (%2F) characters via:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var decodedUrl = decodeURIComponent(string);
and then use a regex:
decodedUrl.match(/[^/]*(?=[?])/)
Mind, that this regex assumes parameters (the part starting with ?...) are present, so if that's not the case, you might have to alter it to your needs.
If the filename always has a .jpg extension:
var url = decodeURIComponent(string);
var filename = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf(".jpg"))
If not:
url = url.substring(url.lastIndexOf("/")+1)
filename = url.substring(0,url.indexOf("?"))
Looking at the string, it appears that the file name is between the second occurrence of "%2F" and the first occurrence of "?" in the string.
The first step is to get rid of the part of the string before the second "%2F". This can be done by splitting the string at every "%2F" and taking the third element in the resulting array.
var intermediate = string.split("%2F")[2]
Then, we need to get rid of everything after the "?":
var file_name = intermediate.split("?")[0]
This should give you the file name from the URL

remove last two parameters from URL

i want to break a following url
http://www.example.com?name=john&token=3425kkhh34l4345jjjhjhj&uid=09900434&cn=bella&cjid=3344324
into this by eliminating last two parametes i.e. &cn=bella&cjid=3344324
http://www.example.com?name=john&token=3425kkhh34l4345jjjhjhj&uid=09900434
the length of the url may change but the last two parameters remains in that position only. so how can i remove that in a efficient way.
A RegExp is the easiest way for this case:
str = str.replace(/&[^&]*&[^&]*$/,'');
You can use replace with regular expression. If the url is in var url then you can use this one
var new_url = url.replace(/&cn=.*/, '');
you can test it with
var url = 'http:\www.example.com?name=john&token=3425kkhh34l4345jjjhjhj&uid=09900434&cn=bella&cjid=3344324';
console.info(url.replace(/&cn=.*/, ''));
var string = "http://dom.com/?one=1&two=2&three=3&four=4";
string.match(/(.*)&(.*)&(.*)/)[1]; // strips last two parameters
You can use regular expressions to replace the last 2 parameters with the empty string:
var url = "http://www.example.com/?p1=1&p2=2&p3=3&p4=4";
var urlWithoutLast2Parameters = url.replace(/&[^&]+&[^&]+$/,"");
You could use the function IndexOf to find the location of the '&cn' and then just use the substring function to create a new string eliminating the '&cn' portion of the URL, so something like...
var intIndexOf = str.IndexOf('&cn=')
strURL = strURL.substring(0,intCharAt)

change domain portion of links with javascript or jquery

Sorry for my original question being unclear, hopefully by rewording I can better explain what I want to do.
Because of this I need a way to use JavaScript (or jQuery) to do the following:
determine domain of the current page being accessed
identify all the links on the page that use the domain www.domain1.com and replace with www.domain2.com
i.e. if the user is accessing www.domain2.com/index then:
Test 1
should be rewritten dynamically on load to
Test 1
Is it even possible to rewrite only a portion of the url in an href tag?
Your code will loop over all links on the page. Here's a version that only iterates over URLS that need to be replaced.
var linkRewriter = function(a, b) {
$('a[href*="' + a + '"]').each(function() {
$(this).attr('href', $(this).attr('href').replace(a, b));
});
};
linkRewriter('originalDomain.com', 'rewrittenDomain.com');
I figured out how to make this work.
<script type="text/javascript">
// link rewriter
$(document).ready (
function link_rewriter(){
var hostadd = location.host;
var vendor = '999.99.999.9';
var localaccess = 'somesite1.';
if (hostadd == vendor) {
$("a").each(function(){
var o = $(this);
var href = o.attr('href');
var newhref;
newhref = href.replace(/somesite1/i, "999.99.999.99");
o.attr('href',newhref);
});
}
}
);
</script>
You'll need to involve Java or something server-side to get the IP address. See this:
http://javascript.about.com/library/blip.htm
Replace urls domains using REGEX
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.

Categories

Resources