Last Segment before the question mark ( ? ) in Javascript - javascript

Here is the URL
http://localhost:8080/BIM/teacher/reports/section-exercise/assignment?assessmentId=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a
I want to grab the last segment of my URL before the ?, ignore what after the ?
Can someone please teach me how to do that ?
I've tried
var href = location.href;
var lastSegment = href.substr(href.lastIndexOf('/') + 1);
console.log(lastSegment);
I got
assignment?assessmentId=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a
I only want assignment

Try this
var pathParts = location.pathname.split('/'),
basename = pathParts[pathParts.length - 1];
Or this super handy one-liner (sometimes I have to remind myself that arrays have methods)
var basename = location.pathname.split('/').pop();
See URLUtils.pathname

var lastSegment = href.substring(href.lastIndexOf('/') + 1, href.lastIndexOf('?'));
You have to also limit your end - and use substring instead of substr.
Here's a fiddle too ;)
http://jsfiddle.net/jf2xrahx/

Try utilizing String.prototype.match()
var url = "http://localhost:8080/BIM/teacher/reports/section-exercise/assignment?assessmentId=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a";
var res = url.match(/\w+\?/)[0].slice(0, -1);
document.write(res);

Related

replace a string partially with something else

lets say I have this image address like
https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
how is it possible to replace FILE_NAME.jpg with THUMB_FILE_NAME.jpg
Note: FILE_NAME and THUMB_FILE_NAME are not static and fix.
the FILE_NAME is not fixed and I can't use string.replace method.
eventually I don't know the File_Name
Use replace
.replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME")
or if you want to support multiple formats
.replace(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g, "THUMB_FILE_NAME")
Demo
var output = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b".replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME");
console.log( output );
Explanation
(?<=\/) matches / but doesn't remember the match
[^\/]* matches till you find next /
(?=(.jpg) ensures that match ends with .jpg
To match the FILE_NAME, use
.match(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g)
var pattern = /[\w-]+\.(jpg|png|txt)/
var c = 'https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
'
c.replace(pattern, 'YOUR_FILE_NAME.jpg')
you can add any format in the pipe operator
You can use the String's replace method.
var a = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
a = a.replace('FILE_NAME', 'THUMB_FILE_NAME');
If you know the format, you can use the split and join to replace the FILE_NAME.
let str = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
let str_pieces = str.split('/');
let str_last = str_pieces[str_pieces.length - 1];
let str_last_pieces = str_last.split('?');
str_last_pieces[0] = 'THUMB_' + str_last_pieces[0];
str_last = str_last_pieces.join('?');
str_pieces[str_pieces.length - 1] = str_last;
str = str_pieces.join('/');

What's the best way to increment a string [jQuery]

I have a variable that returns me the url of an image, and in this url the id of the image can vary the quantity of numbers... what would be the best way to complement the id like this:
As it is: http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg
How to stay: http://mydomain.com.br/arquivos/ids/1318090-500-500/94842_1.jpg
In short, I need to add the "-500-500" into id
Sorry... A Example:
var a = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var b = "-500-500";
var position = 43;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
You can do something like following:
var url = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var index = url.lastIndexOf("/");
var new_url = url.slice(0, index) + "-500-500" + url.slice(index);
link = link.split("/").reduce((r,c,i)=>r+c+i===5?"-500-500": "","").join("/");
Simply add it behind the 6th element ( that are seperated by / ) .
you have not shown any progress what you did! How about i gave you the hint?
assign a variable to your string, split it using \ and then find the exact occurrence to change by this [0] of course change the number according to your desire where change is required.
Now get your new string and concate with old in a way that you get desired results. Example
var str = "http://mydomain.com.br/arquivos/ids/1318090/94842_1.jpg";
var newstr = str.split('/')[5];
var prepstr = newstr + "something";
then finally,
str + prepstr;

How to extract last value in the URL before the last / separator using JQuery

I have this URL:
http://test.com/en/country/city
Im using lastIndexOf to obtain "city" but I want to obtain "country"
window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
Is this posible with lasIndexOf or there is another function available for this case?
Thank you in advance!
You can split your url by / and take needed element (first remove http:// part):
var str = 'http://test.com/en/country/city';
str = str.replace('http://', '');
var parts = str.split('/');
console.log(parts);
alert(parts[2]+', '+parts[3]);
Try:
var fragment = "http://test.com/en/country/city";
var array_fragment = fragment.split('/');
var city = array_fragment[array_fragment.length - 1]
var country = array_fragment[array_fragment.length - 2]
alert(country)
You could do something like this:
var url = "http://test.com/en/country/city"
var urlParts = url.split("/")
urlParts[urlParts.length - 1] (which would equal to "city")
urlParts[urlParts.length - 2] (which would equal to "country")
Basically split on each occurence of "/" and pick the correct item from the returned array.
Is this posible with lastIndexOf?
Yes, it is possible.
Let's say
x="http://test.com/en/country/city"
We get the position of the last /
y=x.lastIndexOf("/");//26
We get the position of the second last /
z=x.lastIndexOf("/",y-1);//18
To extract the country, we now use substring as follows
x.substring(z+1,y)//country
Use split function to get second last value.
Try this
var url='http://test.com/en/country/city';
var splitArray=url.split('/');
alert(splitArray[splitArray.length-2]);
Try something like this.
var url = window.location.href;
var urlArray = url.split("/");
urlArray[urlArray.length-1] //City
urlArray[urlArray.length-2] //Country

Single regexp to get page URL but exclude port number from a full URL

I'm trying to come up with a regexp to get the page URL from the full URL but exclude a possible port number from it. So far I came up with the following JS:
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#]+)/i);
if(res)
{
var pageURL = res[1];
console.log(pageURL);
}
If I call it for this:
var url = "http://www.example.com/php/page.php?what=sw#print";
I get the correct answer: example.com/php/page.php
But if I do:
var url = "http://www.example.com:80/php/page.php?what=sw#print";
I need it to return example.com/php/page.php instead of example.com:80/php/page.php.
I can remove it with the second regexp, but I was curious if I could do it with just one (for speed)?
You can modify your regex to this:
/^.*\:\/\/(?:www2?.)?([^/:]+)(?:[^:]*:\d+)?([^?#]+)/i
RegEx Demo
It will return 2 matches:
1: example.com
2: /php/page.php
as match[1] and match[2] respectively for both inputs that you can concatenate.
http://www.example.com/php/page.php?what=sw#print
OR
http://www.example.com:80/php/page.php?what=sw#print
Update: Here are performance results on jsperf.com that shows regex method is fastest is of all.
Keep it simple:
~ node
> "http://www.example.com:3000/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
> "http://www.example.com/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
Why would you use a regex at all?
EDIT:
As pointed out by #c00000fd: Because document might not be available and document.createElement is very slow compared to RegExp - see:
http://jsperf.com/url-parsing/5
http://jsperf.com/hostname-from-url
Nevertheless I will leave my original answer for reference.
ORIGINAL ANSWER:
Instead you could just use the Anchor element:
Fiddle:
http://jsfiddle.net/12qjqx7n/
JS:
var url = 'http://foo:bar#www.example.com:8080/php/page.php?what=sw#print'
var a = document.createElement('a');
a.href = url;
console.log(a.hash);
console.log(a.host);
console.log(a.hostname);
console.log(a.origin);
console.log(a.password);
console.log(a.pathname);
console.log(a.port);
console.log(a.protocol);
console.log(a.search);
console.log(a.username);
Additional information:
http://www.w3schools.com/jsref/dom_obj_anchor.asp
How about a group for matching the port, if present?
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#\/:]+)(\:\d+)?(\/[^?#]+)/i);
if(res)
{
var pageURL = res[1]+res[3];
console.log(res, pageURL);
}
Try
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
document.body.innerText = res;
You could use replace method to modify your original string or Url,
> var url = "http://www.example.com/php/page.php?what=sw#print";
undefined
> var url1 = "http://www.example.com:80/php/page.php?what=sw#print";
undefined
> url.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
> url1.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
DEMO

Extract part of current url to use in javascript function

hoping someone who knows a bit about javascript maybe able to help me. I need to extract part of the url of my pagepage to use in a javascript function and append to a url. ( it's for a power reviews setup.) the portion i need to extract is the number of the example below ie. www.mydomain.com/my-product-could-be-i950.html -- so would just need the 950 part.. the number part could be 2,3,4 characters. I then need to append this to the url www.mydomain.com/write-a-review.html?pr_page_id=950
could anyone help, it's a bit beyond me this one to be honest..
Many thanks.. Nathan
var num = location.pathname.match(/(\d+)\.html$/);
if( num ) {
var url = 'www.mydomain.com/write-a-review.html?pr_page_id=' + num[1];
}
Try this:
<script type="text/javascript">
function changeURL()
{
var szURL = location.pathname;
szURL = "www.mydomain.com/my-product-could-be-i950.html";
var num = szURL.replace(/\D/gi, "");
szURL = "www.mydomain.com/write-a-review.html?pr_page_id=" + num;
//Set URL
}
</script>
you could use regex:
var re = /i([0-9]{2,4})\.html$/;
var m = document.location.match(re);
if (m){
document.location.href = 'http://www.mydomain.com/write-a-review.html?pr_page_id='+m[1];
}
//current page URL
cur = window.location
//regex to match your number
regex = /i[0-9]{2,4}\.html/;
//your number
num = cur.match(regex);
alert(num);
Not tested, Note that the variable num could be an array.

Categories

Resources