[Javascript] Change Extensions

Shawn Milo shawn.milo at gmail.com
Thu Aug 25 12:46:40 CDT 2005


On 8/25/05, Falls, Travis D (HTSC, CASD) <Travis.Falls at thehartford.com> wrote:
> I am trying to write a javascript method that will use regular expressions
> to figure out the file extension of a file name (String) and change it.
> Basically I need to find ".*" and replace it with ".working"  I don't know
> how to write this regular expression though.  Can someone explain how to do
> this? (not just send over the regular expression I want to learn how to do
> this).  Thanks.


Travis,

You want a regex that says:
"Find the last period, then remember everything after that."

In regex syntax, a period is a reserved character, so you have to
"escape" it with
a backslash (so it would be \. instead of .).

So you have:   /\./   (A regex is put inside forward slashes.)

Now, you want to make sure it's the last period. Easy. The special
character '.' (the period) matches any character. The asterisk (*)
matches zero or more. So look for zero or more characters followed by
a period.

 /.*\./   (Note that due to "greedy matching," the .* will match any
and all periods up to the last, so you don't have to worry about it
stopping early.)

Now, you want to find everything after the last period. Easy, another '.*'.

  /.*\..*/

Surround the part you want to replace with parenthesis.

 /.*\.(.*)/

Use good clean syntax, and specify the beginning of line (^) and end
of line ($).

 /^.*\.(.*)$/

So if you want to remember what it was before you replace it, you can
reference it like this:

oldExt = = strng.replace(/^.*\.(.*)$/, '$1')     ($1 refers to
whatever is in the first set of parenthesis.

Change the position of the parenthesis to capture the filename minus
the extention:

/^(.*\.).*$/
newName = strng.replace(/^(.*\.).*$/, '$1.working')  (The period
needn't be escaped here.)

Use a better regex, and match both:

/^(.*\.)(.*)$/
oldExt = = strng.replace(/^(.*\.)(.*)$/, '$2')
newName = strng.replace(/^(.*\.)(.*)$/, '$1.working')

Please let me know if you have any questions. I just typed all of this
off of the top of my head, so it's possible there will be a syntax
error or something. But I'll help you work through any problems (yours
or mine).

Shawn



More information about the Javascript mailing list