Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Insert a word before the file name's dot extension in JavaScript?
To insert a word before a file's extension, you can split the filename on the dot (.) and then reconstruct it with the new word. This technique is useful for creating versioned files, adding timestamps, or modifying filenames programmatically.
Basic Example
Let's start with a simple example where we insert "programming" before the ".js" extension:
var actualJavaScriptFileName = "demo.js";
var addValueBetweenFileNameAndExtensions = "programming";
console.log("The actual File name = " + actualJavaScriptFileName);
var [fileName, fileExtension] = actualJavaScriptFileName.split('.');
var modifiedFileName = `${fileName}-${addValueBetweenFileNameAndExtensions}.${fileExtension}`;
console.log("After adding into the file name:");
console.log(modifiedFileName);
The actual File name = demo.js After adding into the file name: demo-programming.js
Using a Reusable Function
For better code organization, create a function that can handle different filenames and words:
function insertWordBeforeExtension(filename, word) {
var [name, extension] = filename.split('.');
return `${name}-${word}.${extension}`;
}
// Test with different files
console.log(insertWordBeforeExtension("script.js", "minified"));
console.log(insertWordBeforeExtension("style.css", "responsive"));
console.log(insertWordBeforeExtension("image.png", "thumbnail"));
script-minified.js style-responsive.css image-thumbnail.png
Handling Files with Multiple Dots
For filenames with multiple dots (like "jquery.min.js"), use a more robust approach:
function insertWordBeforeExtensionSafe(filename, word) {
var lastDotIndex = filename.lastIndexOf('.');
if (lastDotIndex === -1) {
// No extension found
return `${filename}-${word}`;
}
var name = filename.substring(0, lastDotIndex);
var extension = filename.substring(lastDotIndex);
return `${name}-${word}${extension}`;
}
// Test with complex filenames
console.log(insertWordBeforeExtensionSafe("jquery.min.js", "v3"));
console.log(insertWordBeforeExtensionSafe("config.dev.json", "backup"));
console.log(insertWordBeforeExtensionSafe("README", "updated"));
jquery.min-v3.js config.dev-backup.json README-updated
Comparison of Methods
| Method | Handles Multiple Dots? | Best For |
|---|---|---|
| split('.') | No | Simple filenames with single extension |
| lastIndexOf('.') | Yes | Complex filenames, production code |
Conclusion
Use split('.') for simple cases or lastIndexOf('.') for robust filename handling. The lastIndexOf method is recommended for production applications as it properly handles complex filenames.
