Can the below code be done in one line? Do you think it should or is it ok like this?
function() {
var str = {{Click URL}};
var str1 = str.split('/').pop();
return str1.charAt(0).toUpperCase() + str1.slice(1);
}
Seems alright, though the names str
and str1
aren't very descriptive names. Also, indentation is inconsistent.
I'd also point out that your code obviously isn't real code (which technically makes it off-topic for Code Review) due to the {{Click URL}}
. I can still tell what's going on, but in the future, post the real code. Or at least post a working piece of code where the function takes a URL as its argument or something, rather than having a hard-coded syntax error!
But beyond that: URLs can be complex. While I'm sure this is built for a very specific purpose, and you're expecting URLs that look a certain way, it'd be nice to make it more robust.
Firstly, the URL can have a trailing slash which would cause your code to find an empty string.
Also, a URL can have a query string like ?foo=bar
or a hash/fragment like #heading-2
appended. Your code would treat such things as part of the last "word" in the URL (or maybe the query string contains slashes too, which would split the URL in the wrong place).
Lastly, URLs can contain percent-encoded characters, which won't be decoded by your function.
Some test cases:
http://example.com/something => "Something"
http://example.com/something/ => ""
http://example.com/something?q=foo => "Something?q=foo"
http://example.com/something#id123 => "Something#id123"
http://example.com/something?q=foo#123 => "Something?q=foo#123"
http://example.com/some%20thing => "Some%20thing"
http://example.com/something/#id123 => "#id123"
http://example.com/some%20thing?q=foo => "Some%20thing?q=foo"
I trust you can see the problem.
Something like this is more robust, though I don't guarantee it's bullet-proof:
function lastWordCapitalized(url) {
return url.replace(/^.*\/([^?#\/]+).*$/, function (_, word) {
var word = decodeURI(word);
return word.charAt(0).toUpperCase() + word.slice(1);
});
}
Which returns
http://example.com/something => "Something"
http://example.com/something/ => "Something"
http://example.com/something?q=foo => "Something"
http://example.com/something#id123 => "Something"
http://example.com/something?q=foo#123 => "Something"
http://example.com/some%20thing => "Some thing"
http://example.com/something/#id123 => "Something"
http://example.com/some%20thing?q=foo => "Some thing"
I should add, that all of this is assuming that
href
might just be ".."
, which is perfectly valid, but in which case there isn't much to display.http://example.com/
), you'll just end up upcasing the domain name.