Permalink
Browse files

Adding goog.string.path#extension method.

R=nnaze
DELTA=41 (41 added, 0 deleted, 0 changed)


Revision created by MOE tool push_codebase.
MOE_MIGRATION=6190


git-svn-id: http://closure-library.googlecode.com/svn/trunk@2460 0b95b8e8-c90f-11de-9d4f-f947ee5921c8
  • Loading branch information...
1 parent 752adff commit 999e56a6a0976de62e8aa9646857dc15da5afcf1 dpapad@google.com committed Jan 23, 2013
Showing with 41 additions and 0 deletions.
  1. +14 −0 closure/goog/string/path.js
  2. +27 −0 closure/goog/string/path_test.html
@@ -56,6 +56,20 @@ goog.string.path.dirname = function(path) {
/**
+ * Extracts the extension part of a pathname.
+ * @param {string} path The path name to process.
+ * @return {string} The extension if any, otherwise the empty string.
+ */
+goog.string.path.extension = function(path) {
+ var separator = '.';
+ // Combining all adjacent periods in the basename to a single period.
+ var basename = goog.string.path.basename(path).replace(/\.+/g, separator);
+ var separatorIndex = basename.lastIndexOf(separator);
+ return separatorIndex <= 0 ? '' : basename.substr(separatorIndex + 1);
+};
+
+
+/**
* Joins one or more path components (e.g. 'foo/' and 'bar' make 'foo/bar').
* An absolute component will discard all previous component.
* See http://docs.python.org/library/os.path.html#os.path.join
@@ -77,6 +77,33 @@
assertArrayEquals(['//foo', 'bar'], goog.string.path.split('//foo//bar'));
}
+function testExtension() {
+ assertEquals('jpg', goog.string.path.extension('././foo/bar/baz.jpg'));
+ assertEquals('jpg', goog.string.path.extension('././foo bar/baz.jpg'));
+ assertEquals('jpg', goog.string.path.extension(
+ 'foo/bar/baz/blah blah.jpg'));
+ assertEquals('', goog.string.path.extension('../../foo/bar/baz baz'));
+ assertEquals('', goog.string.path.extension('../../foo bar/baz baz'));
+ assertEquals('', goog.string.path.extension('foo/bar/.'));
+ assertEquals('', goog.string.path.extension(' '));
+ assertEquals('', goog.string.path.extension(''));
+ assertEquals('', goog.string.path.extension('/home/username/.bashrc'));
+
+ // Tests cases taken from python os.path.splitext().
+ assertEquals("bar", goog.string.path.extension("foo.bar"));
+ assertEquals("bar", goog.string.path.extension("foo.boo.bar"));
+ assertEquals("bar", goog.string.path.extension("foo.boo.biff.bar"));
+ assertEquals("rc", goog.string.path.extension(".csh.rc"));
+ assertEquals("", goog.string.path.extension("nodots"));
+ assertEquals("", goog.string.path.extension(".cshrc"));
+ assertEquals("", goog.string.path.extension("...manydots"));
+ assertEquals("ext", goog.string.path.extension("...manydots.ext"));
+ assertEquals("", goog.string.path.extension("."));
+ assertEquals("", goog.string.path.extension(".."));
+ assertEquals("", goog.string.path.extension("........"));
+ assertEquals("", goog.string.path.extension(""));
+}
+
</script>
</body>
</html>

0 comments on commit 999e56a

Please sign in to comment.