I have this url in javascript “/people/things/” I want a function that will only return “things” how do I do this?
I’ve tried ugly stuff. Like iterating but I get stuck when I have to figure out how to delete the rest of the string and its very slow asymptotically.
I keep getting “ILLEGAL”. Super annoying.
$(function() {
var parse = function(str) {
var a = "";
if (str.length && str.length > 1) {
str = str.slice(0, str.length -1); //remove first
for (var i = str.length; i > 1; i--) {
if (str[i] !== '\\' ) {
a += str[i];
}
}
}
return a;
};
c = "\things\stuff\";
alert(parse(c)); //result should be "things"
});
First of all, you could simplify your code using
match()instead:With respect to the
ILLEGALerror, that’s because you forgot to escape the\in your string. So instead of\things\stuff\, use\\things\\stuff\\.Now, to your
parsefunction. The general idea is correct, but you have a couple of implementation errors:breakout of the loop as soon as you find\\(theelsepart of yourif); otherwise, you’ll just skip the\, adding all other characters;a += str[i], usea = str[i] + a.ishould start witha.length - 1, nota.length.Here’s the final version:
DEMO.