获取拆分字符串数组的最后一个元素
I need to get the last element of a split array with multiple separators. The separators are commas and space. If there are no separators it should return the original string.
我需要使用多个分隔符来获取split数组的最后一个元素。分隔符是逗号和空格。如果没有分隔符,则应返回原始字符串。
If the string is "how,are you doing, today?" it should return "today?"
如果字符串是“你今天怎么样?”它应该返回“今天?”
If the input were "hello" the output should be "hello".
如果输入为“hello”,则输出应为“hello”。
How can I do this in JavaScript?
我怎么能用JavaScript做到这一点?
6 个解决方案
#1
82
var str = "hello,how,are,you,today?";
var pieces = str.split(/[\s,]+/);
At this point, pieces
is an array and pieces.length
contains the size of the array so to get the last element of the array, you check pieces[pieces.length-1]
. If there are no commas or spaces it will simply output the string as it was given.
此时,pieces是一个数组,pieces.length包含数组的大小,因此要获取数组的最后一个元素,请检查[pieces.length-1]。如果没有逗号或空格,它将只输出给定的字符串。
alert(pieces[pieces.length-1]); // alerts "today?"
更多相关文章
- 对多维数组中的列进行排序
- “错误:路径必须是字符串”(v5.10.0)
- javascript 截取字符串方法汇总
- JavaScript String(字符串对象)
- JS将字符串转换为数组
- 将textarea值附加到现有数组javascript
- 在变量名是字符串时声明变量?
- ECMAScript6(6):数组的扩展
- 希望日期开始结束在一个数组中的while循环中为一个房间ID