[英]Split string with multiple separators
I have a string where I need to separate it by +-*/ and put it into array. 我有一个字符串,我需要用+ - * /将它分隔成数组。
I've tried this code that I also found here, but it doesn't seem to be working. 我已经尝试过这个代码,我也在这里找到了,但它似乎没有用。 It gives me the error "Invalid regular expression: /+|-|*|//: Nothing to repeat." 它给出了错误“无效的正则表达式:/ + | - | * | //:无需重复。”
var separators = ['+', '-', '*', '/'];
var numbers = x.split(new RegExp(separators.join('|'), ''));
Any advice on how should I do this? 关于我该怎么做的任何建议?
Try this. 尝试这个。
var str = "i-have_six*apples+doyou/know.doe"; console.log(str.split(/[.\\*+-/_]/));
Here is your answer, 这是你的答案,
x = "This+is*test/the*theunder-Yes"; var separators = ['\\\\\\+', '-', '\\\\*', '/']; var numbers = x.split(new RegExp(separators.join('|'),'g')); console.log(numbers);
It is because, your +,* are regex related wild card characters. 这是因为,你的+,*是与正则表达式相关的外卡字符。 You can't use as is. 你不能按原样使用。
use regex split 使用正则表达式拆分
var tempvar = (X).split(/[+-/*]+/);
This should return as array split. 这应该作为数组拆分返回。 eg : X = 1+2-3/4 例如:X = 1 + 2-3 / 4
alert(x) would return as
1,2,3,4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.