Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular Expression Problem 1

Status
Not open for further replies.

greenr02

Programmer
Mar 26, 2002
6
0
0
US
I am trying to use a Regular Expression to pull a file name from a full path into a variable.
Example:
C:\\Documents\Files\FileName.jpg
I want to pull "FileName.jpg" out of this.
I have previously done this in Perl, but the following Perl code just pulls out the 'g' off the end when I use it in Javascript:
/[^\.+]$/
Is it possible to do this in Javascript?
Thanks.
 
Hi,

It is possible using javascript, the first thing you have to do is
1. Get the length of the string
2. Use lastIndexOf property to locate the last occurence of "\" then
3. use For-loop inorder to get the filename starting from the number indicated by lastIndeOf till the end of string.

Hope this helps!
 
yes in order to do that you need to use () to capture the element you want. Your regExp would look like this :

/([^\\][\w\.]+)$/

[^\\] means not ever a \ character
\w means any word character (A-Z, a-z and underscore _)
\. means . character
$ means end of the input.

Here is a working example :

<html>
<head>
<title>finding Filename</title>
</head>
<body>

<form>
<input type=text value=&quot;c:\folder\folder\filename.gif&quot;>
<input type=text value=&quot;RealOne\Extension.ocx&quot;>
</form>

<script>
var trailingName = /([^\\][\w\.]+)$/;

trailingName.test(document.forms[0].elements[0].value)
document.write(RegExp.$1 + &quot;<br>&quot;);

trailingName.test(document.forms[0].elements[1].value)
document.write(RegExp.$1 + &quot;<br>&quot;);

</script>

</body>
</html>

Hope this helps. Gary Haran
 
Many thanks to renzy and xutopia, very helpful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top