如何在javascript中拆分包含多个分隔符的字符串? [英] How do I split a string with multiple separators in javascript?

查看:215
本文介绍了如何在javascript中拆分包含多个分隔符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中拆分包含多个分隔符的字符串?我试图在逗号和空格上分开但是,AFAIK,JS的分割函数只支持一个分隔符。

How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and spaces but, AFAIK, JS's split function only supports one separator.

推荐答案

传入正则表达式作为参数:

Pass in a regexp as the parameter:

js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!

编辑添加:

您可以通过选择数组的长度减1来获得最后一个元素:

You can get the last element by selecting the length of the array minus 1:

>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"

...如果模式不匹配:

... and if the pattern doesn't match:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"

这篇关于如何在javascript中拆分包含多个分隔符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆