split(/ \s + /)。pop() - 它做了什么? [英] split(/\s+/).pop() - what does it do?

查看:340
本文介绍了split(/ \s + /)。pop() - 它做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能把这个表达翻译成单词吗?

Could you translate this expression to words?

split(/\s+/).pop()

它是在javascript中使用正则表达式来分割字符串,但原理是什么?

It is in javascript and uses regex to split a string, but what are the principles?

推荐答案

这行代码将在空格上分割一个字符串以创建一个单词数组,然后返回最后一个单词。

That line of code will split a string on white space to create an array of words, and then return the last word.

据推测,你已经看到过在某种字符串上使用过这种情况,例如:

Presumably you have seen this used on a string of some kind, e.g.:

var someString = "Hello, how are you today?";
var lastWord = someString.split(/\s+/).pop();

在这种情况下 lastWord 今天?

如果你一次只做一步:

var someString = "Hello, how are you today?";
var words = someString.split(/\s+/);

现在单词是数组: [你好,怎么样,是,你,今天?]

然后:

var lastWord = words.pop();

现在 lastWord 是最后一项数组,即今天?

Now lastWord is the last item from the array, i.e., "today?".

.pop()方法实际上也删除了最后一项从数组中(并返回它),所以在我的第二个例子中,它将改变 words ,这样它将是 [你好,如何,是,你

如果你在我的第一个例子中一行中完成所有内容那么你就不要实际上保持对数组的引用,你只需保留返回的最后一项.pop()

If you do it all in one line as in my first example then you don't ever actually keep a reference to the array, you just keep the last item returned by .pop().

MDN已有关 .split()的更多信息

MDN has more information about .split().

从字符串中获取最后一个单词的另一种方法如下:

Another way to get the last word from a string is as follows:

var lastWord = someString.substr( someString.lastIndexOf(" ") + 1 );

这篇关于split(/ \s + /)。pop() - 它做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆