Javascript strings : Appending django urls - javascript

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/

Related

Using split to get only the URL without query string in 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);

Replace within a string, Javascript

I am having some issues with the simple .replace() function from JS.
Here is my code
console.log(URL);
URL.replace("-","/");
console.log(URL);
Here is my output:
folder1-folder2-folder3
folder1-folder2-folder3
the second one should be
folder1/folder2/folder3
right?
If you guys need from my code, please let me know :)
Thanks in advance,
Bram
The correct thing is to replace it with a global regex with g after the regex that in this case is /-/
console.log(URL);
URL = URL.replace(/-/g,"/");
console.log(URL);
Replace returns a new string after replacement. It does not alter the string that replace was called on. Try this:
console.log(URL);
URL = URL.replace("-","/");
console.log(URL);
To replace all occurences look at this How to replace all occurrences of a string in JavaScript?
console.log(URL);
URL = URL.replace(/-/g, '/');
console.log(URL);

Javascript - "history.pushState" replaces regular "&" with "&". How to avoid it?

I am doing an AJAX request in Rails and after executing it, I'd like to modify the URL and put there all there parameters.
So this is how I obtained the relative URL in the Rails controller:
#url_params = request.original_fullpath
# => /members/info/detail?currency=usd&year=2016
Then, in the JS file:
console.log("<%= #url_params %>");
# => /members/info/detail?currency=usd&year=2016
So I tried:
var url = "<%= #url_params %>";
var replaced_url = url.replace("&", "&");
# => /members/info/detail?currency=usd&year=2016
but it doesn't work neither.
When I do history.pushState("", "", replaced_url);, in the URL is still the $amp; instead of only &.
How to push the URL without the & characters?
Thank you
I believe by default rails html encodes your output to get the unencoded output try
var url = "<%=raw #url_params %>";
change
var replaced_url = url.replace("&", "&");
to
var replaced_url = url.replace(/&/g, '&');
it seems like, url has multiple &'s, because of which single replacement of string would not work, so consider group replace for such things.
know more about : http://www.w3schools.com/jsref/jsref_replace.asp

How to get the main domain string using regular expression?

I have just started using regular expression and i landed up in a problem. So it would be really nice if someone can help me out with it.
The problem is, in case I have a url as given below;
$url = http://www.blog.domain.com/page/category=?
and want only the domain, how can i get it using regular expression in javascript.
thank you
This should work too, but most restrictive and shorter:
var url = "http://www.blog.domain.com/page/category"
var result = url.replace(/^(https?:\/\/)?(.+\.)*(([a-z0-9-]*)\.[a-z]{2,6})(\/.+)$/i,"$4")
If you want "domain.com" and not only "domain", use $3 instead of $4.
Explaination step by step:
A correct domain syntax: letters,numbers and "-" /([a-z0-9-]*)/i
Domain extension (2-6 chars): /(([a-z0-9-]*)\.[a-z]{2,6})/i
Subdomains: /(.+\.)*(([a-z0-9-]*)\.[a-z]{2,6})/i
An url start with http and maybe https: /^https?:\/\/(.+\.)*(([a-z0-9-]*)\.[a-z]{2,6})/i
You can put or not http when you type an url: /^(https?:\/\/)?(.+\.)*(([a-z0-9-]*)\.[a-z]{2,6})/i
Then what is after /: /^(https?:\/\/)?(.+\.)*(([a-z0-9-]*)\.[a-z]{2,6})(\/.+)$/i
Try below code
var url = "http://www.blog.domain.com/page/category=?";
var match = url .match(/(?:http?:\/\/)?(?:www\.)?(.*?)\//);
console.log(match[match.length-1]);
You can get it using the following RegEx: /.*\.(.+)\.[com|org|gov]/
You can add all of the supported domain extensions in this regex.
RegEx101 Explanation
Working Code Snippet:
var url = "http://www.blog.domain.gov/page/category=?";
var regEx = /.*\.(.+)\.[com|org|gov]/;
alert(url.match(regEx)[1]);
Do not use regex for this:
use hostname:
The URLUtils.hostname property is a DOMString containing the domain of
the URL.
var x = new URL("http://www.blog.domain.com/page/category=?").hostname;
console.log(x);
as pointed by vishwanath, URL faces compatibilty issues with IE<10 so for those cases, regex will be needed.
use this :
var str = "http://www.blog.domain.com/page/category=?";
var res = str.match(/[^.]*.(com|net|org|info|coop|int|co\.uk|org\.uk|ac\.uk|uk)/g);
console.log(res);
=> domain.com
the list in the regex can be expanded further depending upon your need.
a list of TLDs can be found here

Javascript replacing /, str.replace not working

I'm having a really stupid issue where javascript is replacing every '/' with '%2F' in a url. Here is what i have now:
var url;
url = $(this).val();
url = str.replace('%2F', '/');
window.location.href = $(this).val();
What have I done wrong here?
You need to decode the url to convert the special characters back to what they should be (like changing %2F back to /). To do this, you can use decodeURI:
url = $(this).val();
url = decodeURI(url);
However, sometimes spaces get replaced by + instead of %20. So, to handle these cases, you must replace all + with %20 before decoding your url.
url = $(this).val();
url = url.replace('+', '%20');
url = decodeURI(url);
And now url is the decoded version of the url.

Categories

Resources