Question

I want to add a hashstring to file name, so I'm trying to rename the string.

This is what I have:

var x = "puh.jpg";
var y = x.split(".");
y.splice(1,0,"foo");
var z = y.join(".");
console.log(z)

Which correctly returns: puh.foo.jpg.

Question:
Can this be done in a single line and without having to declare helper variables?

Thanks!

Was it helpful?

Solution

You can do it with a regex pretty easily (modulo the complexity of names you need to work with):

var y = x.replace(/^([^.]*)\.(.*)$/, '$1.foo.$2');

In the regular expression, I've used ( ) to create groups (2 of them). The first group matches all the characters in the name except for periods, up to the . separating the name from the file extension. (If the extension might not be present at all, then it would look like ^([^.]*)\.?(.*)$ instead, to make the "." optional.) The second group gets the rest of the name (the extension).

In the replacement string, the constructs "$1" and "$2" are expanded to be the parts of the original string matched by the two groups.

OTHER TIPS

Use this one. It guarantees that the string is injected at the last dot of the file name. It also works if there is no extension.

alert(x.replace(/(\.[^\.]*)?$/, '.foo$1'))

Try it with:

puh.jpg (=> puh.foo.jpg)
puh.bar.jpg (=> puh.bar.foo.jpg)
foo_bar (=> foo_bar.foo)
foo_bar. (=> foo_bar.foo.)

To explain:

  • \. matches a dot
  • [^\.] matches any character other than the dot
  • \.[^\.]* matches a dot followed by zero or more non-dot characters
  • \.[^\.]*$ matches a dot followed by zero or more non-dot characters at the end of the string
  • (\.[^\.]*)$ matches a dot followed by zero or more non-dot characters at the end and allows the dot and the characters to be referred to as a group with $1
  • '.foo$1' replaces the matched characters with .foo followed by the characters themselves

http://jsfiddle.net/HALf6/

x.replace(/\.([a-zA-Z0-9]*)$/, '.foo.$1')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top