Javascript:返回字符串中的最后一个单词

And*_*w P 29 javascript string substring

对它的权利:

我有一个words字符串,其中有两个单词,我需要返回最后一个单词.他们被""分开.我该怎么做呢?

function test(words) {

var n = words.indexOf(" ");
var res = words.substring(n+1,-1);
return res;

}
Run Code Online (Sandbox Code Playgroud)

我被告知要使用indexOf,substring但不是必需的.任何人有一个简单的方法来做到这一点?(有或没有indexOfsubstring)

Jyo*_*ash 49

试试这个:

你可以使用n字长的单词.

例:

  words = "Hello World";
  words = "One Hello World";
  words = "Two Hello World";
  words = "Three Hello World";
Run Code Online (Sandbox Code Playgroud)

所有人都将返回相同的价值:"世界"

function test(words) {
    var n = words.split(" ");
    return n[n.length - 1];

}
Run Code Online (Sandbox Code Playgroud)

  • 使用可以做到这一点```words.trim().split("");``` (8认同)

the*_*eye 28

var data = "Welcome to Stack Overflow";
console.log(data.split(" ").splice(-1));
Run Code Online (Sandbox Code Playgroud)

产量

[ 'Overflow' ]
Run Code Online (Sandbox Code Playgroud)

即使原始字符串中没有空格也可以,因此您可以直接获取这样的元素

var data = "WelcometoStackOverflow";
console.log(data.split(" ").splice(-1)[0]);
Run Code Online (Sandbox Code Playgroud)

产量

WelcometoStackOverflow
Run Code Online (Sandbox Code Playgroud)


use*_*115 25

你也可以:

words.split(" ").pop();
Run Code Online (Sandbox Code Playgroud)

只需链接分割函数的结果(数组)并弹出最后一个元素就可以只用一行就可以了:)


Pau*_* S. 6

您想要最后一个词,它lastIndexOf可能比您更有效indexOf。此外,slice也是Strings可用的方法。

var str = 'foo bar fizz buzz';
str.slice(
    str.lastIndexOf(' ') + 1
); // "buzz"
Run Code Online (Sandbox Code Playgroud)

请参阅 2011年的jsperf,其中显示了split vs indexOf + slice vs indexOf +子字符串该perf显示lastIndexOf的效率与大致相同indexOf,这主要取决于匹配发生的时间。

  • 简短、干净、没有混乱、没有大惊小怪。 (2认同)