Forum Moderators: open
var string="www.mydomain.com/directory/filename.html";
var getit= new Array();
var getit=string.split("directory/");
var result=getit2[1];
var filename=result.split(".");
document.write(filename);
Put that in a file called filename.js and call it via:
<script type='text/javascript' src='http://www.mydomain.com/inc/filename.js'></script>
For online you can use either of these 2 ways. Where str is your url.
function file_name_only(str) {
return str.substring(str.lastIndexOf('/') + 1, str.lastIndexOf('.'))
}or
var myVar = str.substring(str.lastIndexOf('/') + 1, str.lastIndexOf('.'))
Thanks so much for your help! After a bit of trial and error, I got it working. Here's my (your) code in it's final form...
var string=(location.href);
var getit=new Array();
var getit=string.split('directory/');
var result=getit[1];
var filename=result.split('.');
document.write("<a href='http://othersite/otherdirectory/")
document.write(filename[0])
document.write(".php'>click here to see ")
document.write(filename[0])
document.write(" at Othersite.com</a>");
Very cool....my 1st JavaScript!
Thanks again!
The window object contains location and document. Assuming referencing the window isn't necessary, the only thing required in front of location.href would be a reference to another document.
var getit=new Array();
Wouldn't the split() method create an array making that line unrequired? Maybe it's part of something else that didn't get removed in your post?
Lingerboy very nice to see someone enjoying learning. One of the beauties of JavaScript is that there is usually countless ways to come to the same answer. bcolflesh has shown you the use of the split() method. It makes an array from a string. What I posted uses other methods to extract part of a string.
If I'd known you didn't just need a snippet of code I would have written my posts in a way that made it understandable. My apologies for making that assumption. Here is a more readable version of the same thing.
var str = 'www.mydomain.com/directory/filename.html'
var number_1 = str.lastIndexOf('/') + 1
var number_2 = str.lastIndexOf('.')
var myVar = str.substring(number_1, number_2)
document.write(myVar)
Here is a break down starting with the string.
var str = 'www.mydomain.com/directory/filename.html'
The next line finds the numeric position in the string of the first forward slash searching from the end backwards in the string.
var number_1 = str.lastIndexOf('/') + 1
The + 1 at the end says we want the numeric position of the next character after the forward slash (we don't want the forward slash).
The next line does the same as number_1 but looks for a period
var number_2 = str.lastIndexOf('.')
The next line says myVar equals a substring of the original starting from number_1 and ending at number_2
var myVar = str.substring(number_1, number_2)
I'm pretty sure you'll find lots to learn here :) Click on the blue links for examples.
[devguru.com...]