0

如何从这些字符串中获取第一个“单词”?

/User/Edit/
/Admin/Edit/2
/Tags/Add

我应该得到User, Admin, Tags, 等等

http://jsfiddle.net/RV5r2/1/

4

3 回答 3

1

就这么简单。由于您将其拆分为数组,因此只需返回第一个元素:

  return ar[1];

你准备好了;)

或者你可以先 reverse() 然后再 pop() :D 但这可能有点奇怪。只需确保检查数组键 [1] 是否已设置!经过

return (typeof ar[1] !== 'undefined') ? ar[1] : '';
于 2012-07-26T06:50:34.090 回答
0

或者再次:

return ar.slice(1,2);
于 2012-07-26T06:56:35.087 回答
0

我建议您稍微更改 lastWord 方法中的逻辑(注意:lastWord 不是此方法的好名称 - 也许是 firstWord?)以考虑不以“/”开头的路径/字符串和路径不包含“/”

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 "";
    }        
}

这边走 :

  • "/some/amazing/sentence" 将返回 "some"
  • “some/amazing/sentence”将返回“some”
  • “someamazingsentence”将返回“”
于 2012-07-26T07:04:10.403 回答