How To Reliably Get The Filename Without The Suffix In Javascript?
Solution 1:
The replace
function probably is what you want, and it can accept a regular expression as the search pattern:
url = url.replace(/_[^\/]+(\.[^\/]*)$/, "$1");
What that expression does: Example on Regex101
Looks for an
_
that isn't followed by any slashes (so we're only looking at the final segment in the path).Allows any number of non-slash characters after the
_
.Stops matching those at the last
.
it finds followed by zero or more characters (I'm assuming these always have an extension on them); captures the.
and the characters after it (e.g., the extension).Replaces the overall match with just the
.
and extension following it. (The$1
in the replace string is special, it means "use the value of the first capture group.)
If your paths may or may not have an extension on them, just add a ?
near the end of the regex, just before the $
: /_[^\/]+(\.[^\/]*)?$/
(that makes everything in the capture group optional).
Example: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<style>
body {
font-family: monospace;
}
</style>
</head>
<body>
<script>
(function() {
"use strict";
test("http://example.com/uploads/images/a51dd42_thumb.jpg");
test("http://example.com/uploads/images/a51dd42_s.jpg");
function test(url) {
display("Before: " + url);
url = url.replace(/_[^\/]+(\.[^\/]*)$/, "$1");
display("After: " + url);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
Solution 2:
You can use:
var s = 'http://example.com/uploads/images/a51dd42_thumb.jpg';
var r = s.replace(/^(.+?)_[^.]+(\.[^\/.]+)$/i, '$1$2');
//=> http://example.com/uploads/images/a51dd42.jpg
Solution 3:
Split it easy
var start = Filename.split('_')[0],
file = Filename.split('_')[1],
end = file.split('.')[1];
console.log(start + '.' + end);
.
Post a Comment for "How To Reliably Get The Filename Without The Suffix In Javascript?"