Get specific portion of a URL string - javascript

Here is a working code I have to get a specific portion of a URL string:
const movieName = "frozen_2019";
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
console.log(getSourceError(source)); // result
function getSourceError(source) {
const a = source.substring(source.indexOf(courseName) + courseName.length + 1);
const b = a.substring(a.lastIndexOf("/"));
return a.replace(b , "");
}
Although it's working as expected but I think there should be a cleaner solution to do this...
As you see I want the string between courseName and the file name at the end of the URl.

I'm not completly sure what you mean by cleaner solution but this is a one-liner line with regex supposing you got the same variable names like in your snippet. Is this what you wanted to achieve? You can trim the last and first character to remove the slashes if needed.
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
const courseName = "olaf_is_enjoying_living_his_dream_1";
let extracted = source.match("(?<="+courseName+").*\/");
console.log(extracted);

As you see I want the string between courseName and the file name at
the end of the URL.
When manipulating URL strings, it's often a good idea to split the string into an array using:
let myURLArray = myURLString.split('/');
Then, in this situation, you can use:
indexOf()
splice()
join()
to return the section of the URL that you want.
Working Example:
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
let sourceArray = source.split('/');
let courseNameIndex = sourceArray.indexOf(courseName);
let urlSectionArray = sourceArray.splice((courseNameIndex + 1), ((sourceArray.length - 1) - courseNameIndex - 1));
let urlSection = urlSectionArray.join('/');
console.log(urlSection);

Hi if your source is consinstent with its structure you can split and join the pieces you require.
source.split('/').splice(7,3).join('/')

Related

Vuejs: Handling slicing of select results

let slug = 'test-value/2';
let slug = 'test-value-data/10';
let slug = 'test-number-data/100';
let slug = 'data-test/1000';
let slug = 'test/10000';
For example, each time I select, I will get 1 slug as above. Now I want to trim the string from /number. For example, I want to trim the string test-value/2 to test-value. So how to cut the string from / onwards. And common to all slugs. Please give me your opinion, Thank you.
Try to replace it using regex as shown in the following example :
let slug='test-value/2'
let trimmedSlug=slug.replace(/\/.*/i,'')
console.log(trimmedSlug)
You can use .split()
Note: Use this method if the slug will always have a format of <slug without '/'>/<number>
// Using .split();
let slug = 'test-value/2';
const trimmedSlug = slug.split('/')[0];
console.log(trimmedSlug);

How to extract a string from url using javascript

I have following string:
How can I extract text (i.e.ABC) from the string?
You can try anchorObject.pathname or anchorObject.href.match(/\/([^/]+)$/)[1] if you just want the last path.
You still need to get the anchorObject from the DOM.
const parser = new DOMParser();
const elm = parser.parseFromString('', 'text/html');
const anchorObject = elm.getElementsByTagName('a')[0];
And voilà.
If you are not sure of what the length of the variable you're looking for is, you can use this syntax.
let string = ' ';
console.log(string.split('"')[1].split('/')[3]);
If you know what you're looking for ( for Example: ABC ) you can find index of ABC, and splice the string.
let variable = 'ABC'
console.log(string.substr(string.search("ABC"), variable.length))
Breakdown the string until you get the variable.

Get last two params of an URL - javascript

My URL looks like this
stackoverflow.com/questions/ask/format/return
I need to get only format/return from the above URL. I'm able to assign the complete URL to a variable. Currently i'm doing it on split
url.split("/")[4]
url.split("/")[5]
And this is not Generic. What is the better way to achieve this?
The shortest, cleanest way to do this is by using slice on the splitted URL:
url.split("/").slice(-2).join("/")
Just use the length to help you index from the end:
var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]
A genetic solution,
Var URL = url.split("/"); //
Last = URL[URL.length-1]; // return
LastBefore = URL[URL.length-1]; //format
url = "stackoverflow.com/questions/ask/format/return"
URL = url.split("/");
console.log(URL[URL.length-1]) // return
console.log(URL[URL.length-2]) //format
Look for the last and penultimate values:
let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
I'd parse the url to a URL, then use match on the pathname. This way it will also work should you have any searchparams (?foo=bar) in your url
const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);
Note that you'll get an array holding three entries - 0 being the path combined, 1 the first and 2 the last param.
You can use a simple regex /.*\/(.*\/.*)/) to extract exactly what you want.
str.match(/.*\/(.*\/.*)/).pop()
var str = "stackoverflow.com/questions/ask/format/return",
res = str.match(/.*\/(.*\/.*)/).pop();
console.log(res);
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");

How to strip / replace something from a URL?

I have this URL
http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb
I want to replace the last part of my URL which is c939c38adcf1873299837894214a35eb with something else.
How can I do it?
Try this:
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
somethingelse = 'newhash';
var newUrl = url.substr(0, url.lastIndexOf('/') + 1) + somethingelse;
Note, using the built-in substr and lastIndexOf is far quicker and uses less memory than splitting out the component parts to an Array or using a regular expression.
You can follow this steps:
split the URL with /
replace the last item of array
join the result array using /
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
var res = url.split('/');
res[res.length-1] = 'someValue';
res = res.join('/');
console.log(res);
Using replace we can try:
var url = "http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb";
var replacement = 'blah';
url = url.replace(/(http.*\/).*/, "$1" + replacement);
console.log(url);
We capture everything up to and including the final path separator, then replace with that captured fragment and the new replacement.
Complete guide:
// url
var urlAsString = window.location.href;
// split into route parts
var urlAsPathArray = urlAsString.split("/");
// create a new value
var newValue = "routeValue";
// EITHER update the last parameter
urlAsPathArray[urlAsPathArray.length - 1] = newValue;
// OR replace the last parameter
urlAsPathArray.pop();
urlAsPathArray.push(newValue);
// join the array with the slashes
var newUrl = urlAsPathArray.join("/");
// log
console.log(newUrl);
// output
// http://192.168.22.124:3000/temp/box/routeValue
You could use a regular expression like this:
let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';

How to split a word for getting a specific value in Javascript or Jquery? [duplicate]

How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
If the url is
http://mywebsite/folder/file
how do I only get it to display the "file" part of the url in the alert box?
You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split() does.
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
window.location.pathname.split("/").pop()
The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.
Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:
Input:
const href = 'https://stackoverflow.com/boo?q=foo&s=bar'
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
Output: 'boo'
This works for all common browsers. Only our dying IE doesn't support that (and won't). For IE there is a polyfills available, though (if you care at all).
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
Javascript has the function split associated to string object that can help you:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
Shortest way how to get URL Last Segment with split(), filter() and pop()
function getLastUrlSegment(url) {
return new URL(url).pathname.split('/').filter(Boolean).pop();
}
console.log(getLastUrlSegment(window.location.href));
console.log(getLastUrlSegment('https://x.com/boo'));
console.log(getLastUrlSegment('https://x.com/boo/'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo&s=bar=aaa'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo#this'));
console.log(getLastUrlSegment('https://x.com/last segment with spaces'));
Works for me.
Or you could use a regular expression:
alert(href.replace(/.*\//, ''));
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
I know, it is too late, but for others:
I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like
http://test.com/#/about/us/
or
http://test.com/#sky=blue&grass=green
And with PURL you can easy decide (segment/fsegment) which segment you want to get.
For "classic" last segment you could write:
var url = $.url('http://test.com/dir/index.html?key=value');
var lastSegment = url.segment().pop(); // index.html
Get the Last Segment using RegEx
str.replace(/.*\/(\w+)\/?$/, '$1');
$1 means using the capturing group. using in RegEx (\w+) create the first group then the whole string replace with the capture group.
let str = 'http://mywebsite/folder/file';
let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
console.log(lastSegment);
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).
url.split('/').filter(function (s) { return !!s }).pop()
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.
If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
you can first remove if there is / at the end and then get last part of url
let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href;
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);
targetValue = one
If your url looks like:
http://test.com/one/
or
http://test.com/one
or
http://test.com/one/index.htm
Then loc ends up looking like:
http://test.com/one
Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
// Store original location in loc like: http://test.com/one/ (ending slash)
let loc = "http://test.com/one/index.htm";
console.log("starting loc value = " + loc);
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
let targetValue = loc.substring(loc.lastIndexOf('/') + 1);
console.log("targetValue = " + targetValue);
console.log("loc = " + loc);
Updated raddevus answer :
var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
Prints last path of url as string :
test.com/path-name = path-name
test.com/path-name/ = path-name
I am using regex and split:
var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?")[0]
In the end it will ignore # ? & / ending urls, which happens a lot. Example:
https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm
I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:
[^\/]+[\/]?$
I know it is old but if you want to get this from an URL you could simply use:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname gets the pathname from the current URL.
lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL.
substring will cut the string between two indexes.
if the url is http://localhost/madukaonline/shop.php?shop=79
console.log(location.search); will bring ?shop=79
so the simplest way is to use location.search
you can lookup for more info here
and here
You can do this with simple paths (w/0) querystrings etc.
Granted probably overly complex and probably not performant, but I wanted to use reduce for the fun of it.
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
Split the string on path separators.
Filter out empty string path parts (this could happen with trailing slash in path).
Reduce the array of path parts to the last one.
Adding up to the great Sebastian Barth answer.
if href is a variable that you are parsing, new URL will throw a TypeError so to be in the safe side you should try - catch
try{
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
}catch (error){
//Uups, href wasn't a valid URL (empty string or malformed URL)
console.log('TypeError ->',error);
}
I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
Bestway to get URL Last Segment Remove (-) and (/) also
jQuery(document).ready(function(){
var path = window.location.pathname;
var parts = path.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
lastSegment = lastSegment.replace('-',' ').replace('-',' ');
jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
});
A way to avoid query params
const urlString = "https://stackoverflow.com/last-segment?param=123"
const url = new URL(urlString);
url.search = '';
const lastSegment = url.pathname.split('/').pop();
console.log(lastSegment)

Categories