Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to insert ".js" after the path part of a url?

I have a url variable, in which i'd like to insert ".js" after the path part, UNLESS there is a ".<something>" part after the path already.

So, here's a "hard coded" array of the start values and expected end values for each, which will hopefully illustrate the problem nicely:

var url_pairs = [
 ["http://example.com/foo", "http://example.com/foo.js"],
 ["http://example.com/foo/bars", "http://example.com/foo/bars.js"],
 ["http://example.com/foo/bars?quz=baz",  "http://example.com/foo/bars.js?quz=baz"],
 ["http://example.com/foo/bars?quz=baz&qix=bax", "http://example.com/foo/bars.js?quz=baz&qix=bax"],
 ["/foo", "/foo.js"],
 ["/foo/bars", "/foo/bars.js"],
 ["/foo/bars?quz=baz", "/foo/bars.js?quz=baz"],
 ["/foo/bars?quz=baz&qix=bax", "/foo/bars.js?quz=baz&qix=bax"],
 ["/foo/bars.js?quz=baz&qix=bax", "/foo/bars.js?quz=baz&qix=bax"],
 ["/foo/bars.xml?quz=baz&qix=bax", "/foo/bars.xml?quz=baz&qix=bax"]    
]    

I'm struggling to come up with a clean and quick way to do this, but i'm sure it's possible to do it cleanly and simply eg with a regex. Can anyone set me straight? thanks, Max

EDIT: testing solutions - here's a snippet i wrote to test it.

function convertUrl(oldUrl){
  //insert code to convert oldUrl and return the result
}       

$.each(url_pairs, function(i,pair){
  var oldUrl = pair[0];
  var expected = pair[1];
  var newUrl = convertUrl(oldUrl);
  if(newUrl != expected){
    console.log("expected \""+expected+"\", but got \""+newUrl+"\""); 
  }
});
like image 756
Max Williams Avatar asked Dec 10 '22 21:12

Max Williams


1 Answers

Here's a straightforward regular expression that will do it:

(\/[a-z]+)(\?[a-z=&]+)?$

No need to do any checks; this captures URLs without existing file extensions. Use as such:

var string = "http://example.com/foo/bars?quz=baz&qix=bax";
console.log(string.replace(/(\/[a-z]+)(\?[a-z=&]+)?$/, "$1.js$2"));
// http://example.com/foo/bars.js?quz=baz&qix=bax

EDIT: As requested in the comments, the following updated regex accepts underscores and digits in the path:

(\/[a-z_]+)(\?[0-9a-z_=&]+)?$

Here it is running on all the URLs you provided:

var urls = ["http://example.com/foo",
  "http://example.com/foo/bars",
  "http://example.com/foo/bars?quz=baz",
  "http://example.com/foo/bars?quz=baz&qix=bax",
  "/foo",
  "foo/bars",
  "/foo/bars?quz=baz",
  "/foo/bars?quz=baz&qix=bax",
  "/foo/bars.js?quz=baz&qix=bax",
  "/foo/bars.xml?quz=baz&qix=bax",
  "http://example.com/my_music_world_classes/edit_pupil?id=10199&pupil_id=157721"];
console.log(urls.map(function (url) {
  return url.replace(/(\/[a-z_]+)(\?[0-9a-z_=&]+)?$/, "$1.js$2");
}));
like image 187
Purag Avatar answered Feb 03 '23 00:02

Purag