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.