[英]javascript: grab last string after white space
如果我有一个字符串,其中的任何项目都可以用空格分隔,即:“ ab abc”或“ ab abc abcd”,我该如何设置一个变量以始终抓住最后一块(第一种情况下为abc) ,第二种情况下是abcd)?
Split the array by whitespace. 用空格分割数组。 Grab the last element in the array.
抓住数组中的最后一个元素。
eg. 例如。
s = "the fox went and did something";
arr = s.split(" ");
console.log(arr[arr.length-1]);
You can build a simple function like this: 您可以构建一个简单的函数,如下所示:
function getLastWord(string) {
var newString = string.split(" ");
return newString[newString.length - 1];
}
and the call it with: 并调用它:
var word = getLastWord("My name is Simone"); /* Will result "Simone" */
Try 尝试
var str = "ab abc abcd", _str = str.substring(str.lastIndexOf(" ") + 1)
See String.prototype.substring() , String.prototype.lastIndexOf() 参见String.prototype.substring() , String.prototype.lastIndexOf()
var str = "ab abc abcd", _str = str.substring(str.lastIndexOf(" ") + 1); document.write(_str)
Basic regular expression 基本正则表达式
"asdf asdfffffff".match(/\s([^\s]+)$/)[1]
\\s
Matches whitespace \\s
匹配空格 ([^\\s]+)
Matches series of characters that are not a whitespace ([^\\s]+)
匹配一系列非空格字符 $
Matches end of line $
匹配行尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.