javascript get filename from string - javascript

I want to get the first part of a filename from the full filename, for example, from:
bee_gees_-_stayin_alive.mp3
I want to return: bee_gees_-_stayin_alive
How can I do it?
var filename = file.name;
var name = filename.split('.');
var lastarray = name.length;
var names = filename.split('.')[lastarray];

Get the index of the last period in the string and get the part of the string before that.
Example:
var fullName = "bee_gees_-_stayin_alive.mp3";
var name = fullName.substr(0, fullName.lastIndexOf('.'));
Demo: http://jsfiddle.net/sfB2v/

You should take a look at the very basic form of regular expressions since this question could easily be solved by googling a bit, but here I go:
the dumb way
var filename = "bee_gees_-_stayin_alive.mp3"
var name = filename.split('.')[0]
the proper way
var filename = "bee_gees_-_stayin_alive.mp3"
var name = filename.match(/[a-zA-Z_-]*/)[0]

Related

How to get parts of a URL string using Javascript?

I have this URL:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
now I want to get 2 string from that URL:
#tab-cultura and folclore
how can I get it using Javascript?
url.split('#')[0];
It seems this split is not the right solution:(
"Split" can be correct way to approach this. Pls see below
var url = "mysite.com/categorias/#tab-cultura/folclore/";
let [val1, val2] = url.split('#')[1].split('/')
console.log(val1, val2)
You need to split your URL by / delimiter instead
var url = "mysite.com/categorias/#tab-cultura/folclore/";
var parts = url.split('/');
console.log(parts[2]);
console.log(parts[3]);
Also you can use regex if you don't know position of # in URL
var url = "mysite.com/categorias/category1/category2/#tab-cultura/folclore/";
var parts = url.match(/(#[^\/]+)\/([^\/]+)/);
console.log(parts[1]);
console.log(parts[2]);
With JavaScript’s String.prototype.split function:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
var fields = input.split('/');
var first = fields[0];
var second = fields[1];
var third = fields[2];
var fourth = fields[3];
You can use split('/') like so:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
let [, ,tabCultura, folclore] = url.split('/');
console.log(tabCultura);
console.log(folclore);
Using Array.split() will probably get you what you need — for now, but URLs are inherently quite complicated and you want to make sure the code will function the same way on different servers with variable query parameters etc. It may be more reliable to use built in browser functionality:
const hash = new URL("http://example.com/categorias/#tab-cultura/folclore/").hash
// => "#tab-cultura/folclore/"
hash.split('/')
// => ['#tab-cultura', 'folclore', '']
hash.split('/').filter(i=>i)
// => ['#tab-cultura', 'folclore']
Note: new URL() is not available in IE, but can be polyfilled.

Javascript to grab parts of the URL

I've looked through tons of great posts on pulling query string parameters, and even using regex to grab parts of the URL path. But, it didn't really answer what I'm trying to do.
I need to be able to grab the current URL a user is on and parse out only parts of the pathname, and capture them into separate variables. I don't care about the query string parameters I only want these key parts.
http://www.domain.com/part1/part2/part3/part4
var1=part1
var2=part2
var3=part3
var4=part4
My Javascript is a bit rusty, so any guidance on this would be great!
This solution will split up your string using the slash as a separator, ignoring the protocol.
var url = "http://www.domain.com/part1/part2/part3/part4"
var parts = url.split('/').splice(2);
console.log(parts);
var baseUrl = parts[0];
var part1 = parts[1];
var part2 = parts[2];
var part3 = parts[3];
var part4 = parts[4]
As users in the comments mentioned, the url string is no different than any other string. You can easily just use the string split method to return an array of strings between the / character
To get the href location you can use window.location.href or location.href
var url_str = window.location.href;
The str.split() function takes a separator parameter in this case '/' and returns an array of strings that were found. For example it would return this given your example url http://www.domain.com/part1/part2/part3/part4:
var arr = url_str.split('/');
["http:", "", "www.domain.com", "part1", "part2", "part3", "part4"]
The array .slice(begin,end) method returns a portion of the array from the begin to end(default end of the array) parameters (both zero based, first element = 0, 10th = 9).
To get the last 4 parts of our example array we do the following:
var values = arr.slice(3);
["part1", "part2", "part3", "part4"]
Now you can either access the array directly to get each value or assign them to variables:
console.log("Your first folder is "+values[0]); //direct access
or
var var1 = values[0];
var var2 = values[1];
var var3 = values[2];
var var4 = values[3];
console.log("Your first folder is " + var1]); //variable alias
This is one way to get the url parts like you want.
var url = "http://www.domain.com/part1/part2/part3/part4"
var parts = url.match(/.+w{3}\.\w+\.\w{3}\/(\w+)\/(\w+)\/(\w+)\/(\w+)/);
console.log(parts);
var baseUrl = parts[0];
var part1 = parts[1];
var part2 = parts[2];
var part3 = parts[3];
var part4 = parts[4]
But again, as cyberbit and Patrick have mentioned, you can simply do url.split('/') to get the parts. That way you don't have to worry about how many parts you get in the url. Thanks.

Javascript, insert string into another URL string

Not sure how I would go about writing a formula to do this... I need to do:
current_url = "http://something.random.com/something/something/upload/something/something_else"
new_url = "http://something.random.com/something/something/upload/{NEWSOMETHING}/something/something_else"
Basically I'm always trying to insert another string segment exactly after the upload/ in the original URL. I've thought about using position but I don't have a fixed position because current_url won't always be the same length. The only constant is that I know the string needs to be inserted after upload/, wherever it may be
current_url.replace("upload/","upload/{NEWSOMETHING}/")
If your string is var current_url = "http://something.random.com/something/something/upload/something/c_fit/something_else/c_fit/"; and you want to replace everything in between upload and the last c_fit then current_url.replace(/\/upload\/.*\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/") but you just want to replace between upload and the first c_fit then current_url.replace(/\/upload\/.*?\/c_fit\//,"/upload/"+"<YOUR_STRING>"+"/c_fit/")
var current_url = "http://something.random.com/something/something/upload/something/something_else";
var chunks = current_url.split("/");
var str = [];
var s = chunks.shift();
while(s != "upload"){
str.push(s);
s = chunks.shift();
}
var new_url = str.join('/')+"/upload/{new something}/something/something_else";
alert(new_url);
You could easily split the string on the static text "upload".
var current_url = "http://something.random.com/something/something/upload/something/something_else";
var splitArray = current_url.split("upload");
var additionalParameter = "What_ever_comes_after_upload"
var new_url = splitArray[0] + "upload/" + additionalParameter + splitArray[1];
alert(new_url);

Extract url from javascript String

I would like to extract the following String :
http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg
from this String :
https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg
And before, extract, i would like to check if the global String contains more than one time "http" to be sure to extract the jpg only when needed.
How can i do that ?
Extract the data like this:
var myStr = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg"
var splittedStr = myStr.split("-");
var extractedStr = splittedStr[3].slice(1);
To find out how many "http" is present in the string:
var count = (myStr.match(/http/g)).length;
Hopes it helps
var source = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg"
var temp = source.replace("https","http").split("http");
var result = 'http'+temp[2];
use split()
var original = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg";
original = original.split('-/');
alert($(original)[original.length-1]);
your require URL shows in alert dialog
You can use regex :
str.match(/(http?:\/\/.*\.(?:png|jpg))/i)
FIDDLE

FileName from url excluding querystring

I have a url :
http://www.xyz.com/a/test.jsp?a=b&c=d
How do I get test.jsp of it ?
This should do it:
var path = document.location.pathname,
file = path.substr(path.lastIndexOf('/'));
Reference: document.location, substr, lastIndexOf
I wont just show you the answer, but I'll give you direction to it. First... strip out everything after the "?" by using a string utility and location.href.status (that will give you the querystring). Then what you will be left with will be the URL; get everything after the last "/" (hint: lastindexof).
Use a regular expression.
var urlVal = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var result = /a\/(.*)\?/.exec(urlVal)[1]
the regex returns an array, use [1] to get the test.jsp
This method does not depend on pathname:
<script>
var url = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var file_with_parameters = url.substr(url.lastIndexOf('/') + 1);
var file = file_with_parameters.substr(0, file_with_parameters.lastIndexOf('?'));
// file now contains "test.jsp"
</script>
var your_link = "http://www.xyz.com/a/test.jsp?a=b&c=d";
// strip the query from the link
your_link = your_link.split("?");
your_link = your_link[0];
// get the the test.jsp or whatever is there
var the_part_you_want = your_link.substring(your_link.lastIndexOf("/")+1);
Try this:
/\/([^/]+)$/.exec(window.location.pathname)[1]

Categories

Resources