Click to See Complete Forum and Search --> : Calculation for changing the name of a variable
simmonet
10-02-2003, 10:01 PM
I have a variable that is a URL
ie thisImage.jpg
I want to change the variable to:
thisImage-t.jpg
how do I make the calculation work?
I have to somehow define that the calculation inserts '-t' before the fourth from right character....
TIA
Grant
Khalid Ali
10-03-2003, 07:09 AM
hoping that the image will always have one . (dot operator) the following will work.
var url = "someImage.jpg";
alert("URL ="+url+"\after formatting = "+( url.replace(".","-.") ));
David Harrison
10-03-2003, 08:49 AM
You could use lastIndexOf(".") and then it wouldn't matter if the source of the image had multiple .'s in it's name:
var url = "someImage.jpg";
alert("URL ="+url+"\after formatting = "+url.substring(0,url.lastIndexOf(".")-1)+"-t"+url.substring(url.lastIndexOf(".")-1,url.length));
Or you could shorten it considerably by using regexp:
<script type="text/javascript">
var url = "some.Image.jpg";
alert(url.replace(/\.(\w*)$/g, "-t.$1"));
</script>
David Harrison
10-03-2003, 01:55 PM
I try to avoid using Reg-Exps where the alternative is reasonably short, that way as much of the code as possible will work for older browsers.
By the way, what does the $ sign do? I haven't come accross that before.
And which browsers will regexp not work in? Regexp was implimented in JavaScript 1.2, which was Netscape 3. Not many users running around using Netscape 2, anymore... ;)
Anyway, the $ at the end means to match the end of the string (as we are trying to remove the file extention).
David Harrison
10-03-2003, 02:23 PM
I didn't know which browsers wouldn't support it, I just knew that some wouldn't.
As far as that goes, the difference between browsers that support regexp and browsers that support lastIndexOf and substring (JavaScript 1.0) is marginally small. There will be many, many more that do not support either (13%).
David Harrison
10-03-2003, 04:03 PM
Well like I said, I will use RegExp's when the alternative means going the long way around, eg. filtering out non-numbers from a string.
Unfortunately there's little I can do about the other 13%, doing everything server side is a little impracticle.