[英]Get part of string into variable
i need to get part of string into variable. 我需要将字符串的一部分放入变量。 (note, i will always use exactly 4 names)
(请注意,我将始终使用4个名字)
var names = "Andrew Peter Bob Mark"
I need to get the last one to 我需要拿到最后一个
var last = "Mark"
Thanks for help in advance 预先感谢您的帮助
var last = names.split(/\s+/).pop(); // "Mark"
Explanation: .split
splits a string on a given separator and returns an array. 说明:
.split
在给定的分隔符上分割字符串并返回一个数组。 /\\s+/
is a regular expression for "one or more whitespaces" (space, tab, newline, etc). /\\s+/
是“一个或多个空格”(空格,制表符,换行符等)的正则表达式。 .pop()
grabs the last value from the array that .split
returns. .pop()
从.split
返回的数组中获取最后一个值。
Answer from Roatin Marth is correct, but in case if you need 4 times faster version (in IE) of same operation: Roatin Marth的回答是正确的,但是如果您需要相同操作的4倍更快版本(在IE中):
var last = names.substr(names.lastIndexOf(" "));
It is working without regular expressions and temp arrays - just with index operations of string. 它不使用正则表达式和临时数组就可以工作-仅使用字符串的索引操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.