Remove sections of url to only keep file name - javascript

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.
Code:
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
.replace(/[^a-z\s]/gi, ' ').replace("_", " ")
.replace("subdir", "").toLowerCase().slice(0,-4);

You can do this easily with lastIndexOf():
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"

This function will give you the file name,
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}

From How to catch the end filename only from a path with javascript?
var filename = path.replace(/.*\//, '');
From Getting just the filename from a path with Javascript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);

I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.
Javascript
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
On jsfiddle

You can always Regex to extract data from strings:
The Regex to extract data from URL:
"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"

Related

add to URL after last /

using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.

Extract filename and extension in js

Need a method in JavaScript to extract a filename and extension.
Example:
/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json
returns array: ["tranzila_2018-01-09_08-58-47","json"]
In Node.js
var path = require('path');
function getFilenameAndExtension(pathfilename){
return [path.parse(pathfilename).name, path.parse(pathfilename).ext];
}
In JavaScript
function getFilenameAndExtension(pathfilename){
var filenameextension = pathfilename.replace(/^.*[\\\/]/, '');
var filename = filenameextension.substring(0, filenameextension.lastIndexOf('.'));
var ext = filenameextension.split('.').pop();
return [filename, ext];
}
Result
getFilenameAndExtension("/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json");
//Result -> ["tranzila_2018-01-09_08-58-47", "json"]
It works too if the filename have more than one ".". For example:
getFilenameAndExtension("../log/tranzila.2018-01-09.08-58-47.json");
// Result: ["tranzila.2018-01-09.08-58-47", "json"]
You can use the split() function combined with pop() to get the file full name (name + extension) and detect the separation between your file name and extension with lastIndexOf() :
var str = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';
function fileNameAndExt(str){
var file = str.split('/').pop();
return [file.substr(0,file.lastIndexOf('.')),file.substr(file.lastIndexOf('.')+1,file.length)]
}
console.log(fileNameAndExt(str));
No need to complex Things.
You have a split(" ") method in Javascript that does what you want.
var str = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';
var file = str.split('/').pop();
var fileAndExtensionArray = file.split("."); // This is ["tranzila_2018-01-09_08-58-47","json"]
Short String.prototype.match() solution:
var filepath = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json',
result = (m = filepath.match(/([^/]+)\.([^.]+)$/)) && m.slice(1,3);
console.log(result);
var filepath='/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';
var filename=filepath.split("")[filepath.length-1];
var extension=filename.split(".")[filename.length-1];

Insert a string before the extension in a filename

How can I insert a string before the extension in an image filename? For example, I need to convert this:
../Course/Assess/Responsive_Course_1_1.png
to this:
../Course/Assess/Responsive_Course_1_1_large.png
If we assume that an extension is any series of letters, numbers, underscore or dash after the last dot in the file name, then:
filename = filename.replace(/(\.[\w\d_-]+)$/i, '_large$1');
None of the answers works if file doesn't have extension.
Here's a solution that works for all cases.
function appendToFilename(filename, string){
var dotIndex = filename.lastIndexOf(".");
if (dotIndex == -1) return filename + string;
else return filename.substring(0, dotIndex) + string + filename.substring(dotIndex);
}
Use javascript lastIndexOf, something like:
var s = "Courses/Assess/Responsive_Cousre_1_1.png";
var new_string = s.substring(0, s.lastIndexOf(".")) + "_large" + s.substring(s.lastIndexOf("."));
var s = '../Course/Assess/Responsive_Course_1_1.png'
s.replace(/\.png$/, '_large.png');
This will do the job. By the way, it's night here. :)
UPDATE:
A more general way would be this:
var s = '../Course/Assess/Responsive_Course_1_1.png';
s.replace(/(\.[^\.]+)$/, '_large$1');
Either $1 match a filename with no extension or $2 match an extension.
filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "_large" + '$2');
for files without extension and files includes extension. thanks #paul !
filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "-thumb" + '$2');
If you are not sure what could be the incoming file's extension then this helps:
function renameFileA(imgUrl) {
var extension = `.${imgUrl.split('.').pop()}`
var [fileName] = imgUrl.split(extension);
return `${fileName}_large${extension}`;
};
// this is clean but I don't understand what's going on till I do research ;)
function renameFileB(imgUrl) {
return imgUrl.replace(/(\.[\w\d_-]+)$/i, '_large$1');
};
var valA = renameFileA('http//www.app.com/img/thumbnails/vid-th.png');
var valB = renameFileB('http//www.app.com/img/thumbnails/vid-th.jpg');
console.log('valA', valA);
console.log('valB', valB);
Simple regex replace
filename = filename.replace(/(\.[^.]+)$/i, '_large$1')
Just in case: Flexible to change pattern like prefix or suffix
const url = 'https://example.com/path/filename.png?a&b=c'
const regex = /((?:.+\/.+)+\/)(.?.+)+\.(.+)/
const result1 = url.replace(regex,'$1prefix_$2.$3')
const result2 = url.replace(regex,'$1$2_suffix.$3')
const result3 = '../Course/Assess/Responsive_Course_1_1.png'.replace(regex,'$1$2_large.$3')
const result4 = '../path/file'.replace(/(\/)(.?.+)/,'$1$2_suffix')
console.log(result1) // https://example.com/path/prefix_filename.png?a&b=c
console.log(result2) // https://example.com/path/filename_suffix.png?a&b=c
console.log(result3) // ../Course/Assess/Responsive_Course_1_1_large.png
console.log(result4) // ../path/file_suffix
Credit: Regex from: https://stackoverflow.com/a/60538390/622813

Replace filename using JavaScript?

Can someone show me how to do the following in JavaScript? I know how to grab the src of the image, I just want to be able to replace the filename with something new.
/image/any/path/ANY-TEXT_HERE.png
/image/any/path/NEWTEXT.png
Case-insensitive version:
path = path.replace(/(.*)\/.*(\.png$)/i, '$1/NEWTEXT$2')
Remove the i after / to make it case-sensitive.
Another option:
var filename = "/image/any/path/NEWTEXT.png";
var splitFilename = filename.split("/");
var newPath = splitFilename.slice(0, splitFilename.length - 1).join("/")
if (newPath.length !== 0) {
newPath += "/"
}
newPath += newFilename;
All the other solutions so far assume there actually IS a path. They work only if there is at least one forward slash. This tested functions works in all cases including an empty path:
function rename_img_file(text, newname)
{ // Rename file in a IMG src (no query or fragment)
var re = /^(.*\/)?[^\/]+\.(png|gif|jpe?g)$/i;
var rep_str = '$1' + newname + '.$2';
text = text.replace(re, rep_str);
return text;
}
var url = "/image/any/path/ANY-TEXT_HERE.png";
var mystring = "NEWTEXT";
var ind1 = url .lastIndexOf('/');
var ind2 = url .lastIndexOf('.');
var new_url = url.substring(0,ind1+1 )+ mystring + url.substring(ind2 );
alert(new_url );
javascript its really restrictive to files.
I assume that you want to do that on a server. if that so, you should use a serverside script, not a client side.
Maybe you ar talking about an ajax script
if you can explain a ltl further maybe i can lendyou a hand

Javascript string.replace with regex

I want to replace a url querystring parameter with a new value if it already exists or add it on if not.
e.g.
The current url could be:
a. www.mysite.com/whatever.asp?page=5&version=1 OR
b. www.mysite.com/whatever.asp?version=1
I need the resulting url to be www.mysite.com/whatever.asp?page=1&version=1
I suspect I can use string.replace with a regex to do this the most intelligent way but am hoping for a little help with it from someone more experienced with regexs :) Thanks!
I would rather use location.search along with some .splits() and Array.prototype.somehelp.
var s = location.search.slice(1).split(/&/);
check = s.some(function(elem) {
return elem.split(/=/)[0] === 'page';
});
if(!check) s.push('page=1');
location.href = location.hostname + location.pathname + '?' + s.join('&');
I think the clearest solution would be to write one regex that parses the URL, and then build a URL from there. Here's what I would do:
function urlCleanup(url) {
var match = /http:\/\/www\.mysite\.com\/whatever.asp\?(page=(\d+))?&?(version=(\d+))?/.exec(url);
var page = match[2] ? match[2] : "0";
var version = match[4] ? match[4] : "0";
return "http://www.mysite.com/whatever.asp?page=" + page + "&version=" + version;
}
var testUrls = [ "http://www.mysite.com/whatever.asp?page=4"
, "http://www.mysite.com/whatever.asp?version=5"
, "http://www.mysite.com/whatever.asp?page=4&version=5" ];
for(i in testUrls)
console.log(urlCleanup(testUrls[i]));
One problem this doesn't handle is having the variables in the opposite order in the url (e.g. ?version=5&page=2). To handle that, it would probably make more sense to use two regexes to search the URL for each parameter, like this:
function urlCleanup(url) {
var match, page, version;
match = /version=(\d+)/.exec(url);
version = match ? match[1] : "0";
match = /page=(\d+)/.exec(url);
page = match ? match[1] : "0";
return "http://www.mysite.com/whatever.asp?page=" + page + "&version=" + version;
}
var testUrls = [ "http://www.mysite.com/whatever.asp?page=4"
, "http://www.mysite.com/whatever.asp?version=5"
, "http://www.mysite.com/whatever.asp?version=5&page=2"
, "http://www.mysite.com/whatever.asp?page=4&version=5" ];
for(i in testUrls)
console.log(urlCleanup(testUrls[i]));

Categories

Resources