How can I get the first "word" out of these strings?
/User/Edit/
/Admin/Edit/2
/Tags/Add
I should get User
, Admin
, Tags
, etc
as simple as this. since you split it up in an array, just return the first element:
return ar[1];
and youre ready to go ;)
or you could reverse() first and the pop() :D but this migth be a bit odd. just be sure you check if the array key [1] is set! by
return (typeof ar[1] !== 'undefined') ? ar[1] : '';
还是再次:
return ar.slice(1,2);
I would recommend that you change a bit the logic in your lastWord method ( note : lastWord is not a good name for this method - maybe firstWord?) to take in account paths/strings which don't start with "/" and paths that don't contain "/"
function lastWord(subject)
{
var ar = subject.split("/");
if(ar.length >= 2)
{
//we have at least one / in our string
if(ar[0] !== "") {
//the string doesn't start with /
return ar[0];
}
else {
//if the strings starts with / then the ar[0] will be ""
return ar[1];
}
}
else {
//we return an empty string if the input was not valid, you could handle this differently
return "";
}
}
This way :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.