问题描述
我需要使用多个分隔符来获取split数组的最后一个元素。分隔符是逗号和空格。如果没有分隔符,它应该返回原始字符串。
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.
如果字符串是你今天怎么样,你呢?它应该返回今天?
If the string is "how,are you doing, today?" it should return "today?"
如果输入为hello,则输出应为hello。
If the input were "hello" the output should be "hello".
如何在JavaScript中执行此操作?
How can I do this in JavaScript?
推荐答案
var str = "hello,how,are,you,today?";
var pieces = str.split(/[\s,]+/);
此时,件
是一个数组和 pieces.length
包含数组的大小,以便获取数组的最后一个元素,检查 pieces [pieces.length-1]
。如果没有逗号或空格,它将只输出给定的字符串。
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.
alert(pieces[pieces.length-1]); // alerts "today?"
这篇关于获取拆分字符串数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!