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?"

更多相关文章

  1. 对多维数组中的列进行排序
  2. “错误:路径必须是字符串”(v5.10.0)
  3. javascript 截取字符串方法汇总
  4. JavaScript String(字符串对象)
  5. JS将字符串转换为数组
  6. 将textarea值附加到现有数组javascript
  7. 在变量名是字符串时声明变量?
  8. ECMAScript6(6):数组的扩展
  9. 希望日期开始结束在一个数组中的while循环中为一个房间ID

随机推荐

  1. 解决ArcGIS Android Could not find clas
  2. android 属性android:visibility
  3. Android 回调机制
  4. Android中SQLite数据库操作(1)——使用SQL
  5. Android(安卓)高仿 频道管理----网易、今
  6. android ubuntu下NDK的开发
  7. Android中的布局管理
  8. Android SDK开发 -- TitleBar重构 (代理模
  9. Android 常用样式设置
  10. Android学习之文件存储