How to detect image file extension in a string with JavaScript [duplicate] - javascript

This question already has answers here:
How can I get file extensions with JavaScript?
(36 answers)
Closed 9 years ago.
I would like to know how can I detect an image in a string with JavaScript. For example, I have an input type text that has the following value, "Hey check this out https://exmaple.com/image.jpg" I want to wrap 'https://exmaple.com/image.jpg' in an tag so it can show the image right away in my site. Thank you, I tried using the split function in JavaScript but I don't know how to detect the image extension in the string.

Use lastIndexOf()
var str = "https://example.com/image.jpg";
var dotIndex = str.lastIndexOf('.');
var ext = str.substring(dotIndex);
Fiddle

You'd probably want to use a regular expression like the following in order to find any image type, and make sure you're not returning other junk that you don't want. E.g.
'https://exmaple.com/image.jpg'.match(/[^/]+(jpg|png|gif)$/)
-> ["image.jpg", "jpg"]

var str = "https://example.com/image.jpg";
var extArray = str.split(".");
var ext = extArray[extArray.length - 1];
Try this.
function searchText(text)
{
var arr = text.match("/(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/");
for (var i=0; i<arr.length; i++)
{
//Make tags where 'arr[i]' is your url.
}
}

HINT: (Please use logic based on your needs)
you have to split string somehow based on your condition and check if the string has . or something
var a = "Hey check this out https://exmaple.com/image.jpg";
var text = a.split(' ');
if text array has your condition then assign to variable filename
if(jQuery.inArray(".", text)!==-1) { //i dont prefer only .
filename = text[jQuery.inArray(".", text)];
}
separate the extension
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}

Related

Make javascript as function

i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/

Split last word value in JavaScript string [duplicate]

This question already has answers here:
How to retrieve GET parameters from JavaScript [duplicate]
(17 answers)
Closed 7 years ago.
I have a URL string in JavaScript below ex-
URL-"/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567"
Now, I need to do below 2 things
Check whether the country exists in above url or not and there will be only one countryId in above url
Get the countryId value means 875567.
Thanks Guys for such good response quickly .I got the solution most of the answers are correct.
One More Question Guys I have hyperlink so i am generating some activities when onmousedown event .but the issue is it fires even when i do right click only..but i want the event which fires only on clicking the hyperlink double click or right click and then click
Fetch URL using
window.location.href
And
Split with '?' first, '&' next and '=' so that you can get countryId
OR
directly split with '=' and get last value from array that we get after split
You need to use a combination of indexOf() and substring()
var ind = url.indexOf("countryId");
if (ind != -1){
// value is index of countryid plus length (10)
var countryId = url.substring(ind+10);
}else{
//no countryid
}
How about something like this:
var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
var TheCountry = parseInt(TheString.split('=').pop(), 10);
And then you just need to test if TheCountry is something with if (TheCountry) { ...}
This of course assumes that the URL query string will always have the country ID at the end.
var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
alert((url.match(/countryId/g) || []).length);
alert(url.substring(url.lastIndexOf('=')+1));
you can get the count of the occurrence of any string in first alert and get the countryid value by substring.
This will convert your url query into an object
var data = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
var fieldName = curr.split('=')[0];
var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
prev[fieldName] = value;
return prev
}, {});
then you can just check the value of data.country to get the value
You may also split the string and see if the countryId exists, as below.
var myString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
myString = myString.split("countryId="); //["/MyProject/Information/EmpDetails.aspx?userId=79874&", "875567"]
if (myString.length === 2) {
alert (myString.pop());
}

my replace is not working in my function? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
var jtj_code_lines = []; // this array will hold all the jtj codes line
var JTJ = function(j){
j = j.replace(" ","");
jtj_code_lines = j.split(';'); // splitting all the lines seperated from ;
for(var i=0; i<jtj_code_lines.length; i++){
if(jtj_code_lines[i].charAt(0) === '*'){ // * means that the following word is the name of a method that will perform some action
var q1 = jtj_code_lines[i].replace('*', ''),
q1_pos_1 = q1.indexOf('['); // find the position of the keyword [
var q1_funcname = q1.slice(0, q1_pos_1); // it find the name of that perticular function
if(q1_funcname === "Message"){ // this checks weather the function name is message
var q1_pos_2 = q1.indexOf(']'), // this ifnds the position of keyword ]
q1_func_value = q1.slice(q1_pos_1+1, q1_pos_2); // this finds what is written inside [] and accepts as the value of Message
alert(q1_func_value);
}else{
}
}
}
};
so the above function is pretty simple it finds the specific text written in the braces, i mean that if you write :
JTJ('*Message[hi];')
then it will alert hi and this is quit simple and this is alerting as expected but the problem is coming that if any * is after white space then that perticular thing is not being alerted, so the following have the same condition,*Message[go ]; starts with whitespace so it is not being alerted :
JTJ('*Message[sanmveg];*Message[saini]; *Message[go ];')
but i have a this line j = j.replace(" ",""); to remove all the white spaces, then why it is not working? is there any other way to do this?
thanks.
Fix: j = j.replace(/\s/gi,"");
this would remove all " " with "", in short it would act as replaceAll.
Before it was just replacing first matched " " with "".

In this example how would I make filenames appended with "0000"+1 instead of "0"+1? [duplicate]

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 8 years ago.
I know this is a gimme, but I'm trying to make the filenames serialized with four digits instead of one. This function is for exporting PNG files from layers within Adobe Illustrator. Let me know if you ever need icons - much respect.
var n = document.layers.length;
hideAllLayers ();
for(var i=n-1, k=0; i>=0; i--, k++)
{
//hideAllLayers();
var layer = document.layers[i];
layer.visible = true;
var file = new File(folder.fsName + '/' +filename+ '-' + k +".png");
document.exportFile(file,ExportType.PNG24,options);
layer.visible = false;
}
Use util.printf (see the Acrobat API, page 720):
var file = new File(util.printf("%s/%s-%04d.png", folder.fsName, filename, k));
You can pad your number to the left and take the last four characters like this:
var i = 9;
var num = ("0000"+i);
var str = "filename"+(num.substring(num.length-4)); //filename0009
Or shorter
str = ("0000" + i).slice(-4)
Thanks to this question

Grunt Task - Get Filename from path without extension

Is it possible to get the filename without the extension from the src filepath.
As an example, let's say the src file is my-file.png - located at images/my-file.png.
In my task I have this at the moment:
var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
When I reference filename for output it returns:
images/my-file.png
I want to only return the actual filename, without the path and without the extension:
my-file.png
How can I achieve this?
Might be pretty old but if someone else finds this SO., in reply for #user3143218 's comment :
slice(0, -4) will remove the last 4 characters from the name, so for the example my-file.png we will get my-file but for script.js we will get scrip. I suggest using a regex removing everything from the last dot.
You could use a regex like this:
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.substr(0, theFile.lastIndexOf('.')) || theFile;
That should give you my-file. The regex gives you the string after the last forward slash, and the next line removes everything after the last dot (and the dot).
Thanks to Andeersg's answer below I was able to pull this off. It might not be the best solution but it works. Final code is:
var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.slice(0, -4);
Now onlyName will return:
my-file

Categories