I need to get just the filename without the extension from a url and can't quite get there.
Here's my url in question:
https://www.mealenders.com/shop/index.php/shop/solo-pack.html
Here's what I've tried:
function () {
var value={{Page Path}}.split("/");
return value.reverse()[0];
}
That almost gets me there as it returns "solo-pack.html". What else do I need to do to get rid of the ".html" for this?
Thanks in advance.
You can do the following using javascript. Pop returns the last element which is a string, and then you can use the replace function to get just the filename without .html on the end.
function getFilename () {
return {{ Page Path }}.split('/').pop().replace('.html', '');
}
I see that {{ Page Path }} is probably some templating language but you could modify the above script, to get the current URL and then get the filename as so.
function getFilename () {
return window.location.href.split('/').pop().replace('.html', '');
}
Furthermore you could make it more dynamic to handle any file extension with the following. You need to get the index of the period using indexOf and then sub string from the start of the filename up to the position of the period.
function getFilename () {
var filename = window.location.href.split('/').pop();
return filename.substr(0, filename.lastIndexOf('.');
}
function getFileName(url) {
return url.split("/").pop().split(".")[0];
}
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html";
console.log(getFileName(url));
function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
}
If you need to get rid of any extension, you can use .replace() with regular expression:
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html";
function getFilename (path) {
return path.toString().split('/').pop().replace(/\.\w+$/, '');
}
console.log(getFilename(url));
This will for example change test/index.html into index but index.php.default into index.php and also test.name.with.dots.txt -> test.name.with.dots
Short and sweet:
"https://url/to/file/solo-pack.html".split(/[\\/]/).pop().replace(/\.[^/.]+$/, "")
Returns:
solo-pack
Related
I have multiple javascript files in a folder and I want to make sure that every file has comment in the beginning (that will explain the summary of file).
/*
This file will......
*/
function test () {
....
}
So is this possible using gulp-contains or something else?
I think this would be enough just to make sure if start of a file is the comment initial characters (/*)
gulp.src('./file.js')
.pipe(map(function(file, callback) {
var startWithComment = file.contents.toString().replace(/\n|\r/g, "").trim().startsWith("/*");
if (startWithComment){
// DO YOUR CHORES
}
}))
Another approach is to split the initial text to make sure if it is a valid multi-line comment.
function startsWithValidMultiLineComment(str){
try{
return str.replace(/\n|\r/g, "").trim().split("/*")[1].split("*/")[1].length > 0
} catch (e){
return false;
}
}
Following this approach str.split("/*")[1].split("*/")[0] would be your comment text
By using the regex provided by #Sajjad in previous answer. I have managed to achieve my goal. I have used gulp-if and gulp-fail instead (I find it more flexible).
Here is how I do that:
var condition = function (file) {
sFile = require('path').parse(file.path).name;
var startWithComment = file.contents.toString().replace(/\n|\r/g, "").trim().startsWith("/*");
return (!startWithComment);
}
gulp.task('taskName',
function() {
gulp.src('files/*.js')
.pipe(gulpIf(condition, fail(function () {
var message = 'Some message';
return message;
})));
});
I have a Function (with help of other user of stackoverflow), but only the first if statement works, the second not. I want to take advantage of this code to get both: http and https followed or not by www
function formatURL() {
var url = document.getElementsByName("URL")[0];
var formattedURL = document.getElementsByName("formattedURL")[0];
url = url.value;
if (url.substr(0, 0) === "") // with our without www
{
formattedURL.value = "https://" + url;
return;
} else
{
formattedURL.value = "http://" + url;
return;
}
}
formattedURL.value = url;
}
You're running into this issue because url.substr(0,0) will always be an empty string "" for any string value of url (your if statement is always true).
Not sure what exactly you're trying to compare url.substr against because we don't have all the possible inputs you give to your <URL/> elements. Otherwise, I could have an actual fix for you.
How can I remove "http://" from beginning of a URL inside view in an AngularJS app?
I have URLs in database like:
http://example.com/
http://example.com
example.com
but I only need to show
example.com
inside the view.
This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.
app.filter('domain', function () {
return function (input) {
try {
var url = new URL(input);
return url.hostname;
} catch (DOMException) {
// Malformed URL. Return original (or something else).
return input; }
};
});
URLs that are correct and you might not have thought of:
http://example.com
http://example.com:8000
http://me#example.com
file://example.com
https://example.com
http://example.com/some-path
http://example.com?some-query-url
You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.
use this filter in view
app.filter('domain', function () {
return function (input) {
var output = "",
matches;
var urls = /\w+:\/\/([\w|\.]+)/;
matches = urls.exec( input );
if (matches !== null) output = matches[1];
return output;
};
});
I'm making a js-based epub reader as a weekend project and I'm trying to change the src attribute of the images on each of the book's pages from image urls to data URI's loaded from the epub zip. Here's my function:
//page contents is just an html string of the book's page
pageContents = GlobalZipLoader.load('epub.zip://' + pageLocation);
pageContents = replaceImages(pageContents)
...
function replaceImages(pageContents){
$(pageContents).find('img').each(function(){
var domImage = $(this);
//this is something like ".../Images/img.jpg"
var imageLocation = domImage.attr('src');
//this returns the proper data-uri representation of the image
var dataUri = GlobalZipLoader.loadImage('epub.zip://' + imageLocation);
//this doesn't seem to "stick"
domImage.attr('src', dataUri);
});
return pageContents;
}
The returned pageContents from the replaceImages functions still has the old src attributes. I can provide more detail if needed but any help would be very much appreciated.
Correct answer thanks to The System Restart and Ilia G:
function replaceImages(pageContents) {
newContent = $(pageContent);
... manip ...
return newContent;
}
You don't need to clone it. Simply set pageContents = $(pageContents);, then perform your image replacement on pageContents, then return pageContents.html();
you should try to change the image src after image load complete;
and I think this is happening with in loadImage function.
According to your update question:
You don't need any clone(), I think. Just store pageContents in a tempContents variable and use that variable
Since pageContents is just a string, you'll need to return the modified version of it. Try this:
function replaceImages(pageContents){
// save jQuery object
var $pageContents = $(pageContents);
$pageContents.find('img').each(function(){
var domImage = $(this);
//this is something like ".../Images/img.jpg"
var imageLocation = domImage.attr('src');
//this returns the proper data-uri representation of the image
var dataUri = GlobalZipLoader.loadImage('epub.zip://' + imageLocation);
//this doesn't seem to "stick"
domImage.attr('src', dataUri);
});
// return contents of the modified jQuery object
return $pageContents.html();
}
I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();