jQuery 根据多个分隔符拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19313541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a string based on multiple delimiters
提问by Okky
I was trying to split a string based on multiple delimiters by referring How split a string in jquery with multiple strings as separator
我试图通过引用How split a string in jquery with multiple strings as separator来根据多个分隔符拆分字符串
Since multiple delimiters I decided to follow
由于多个分隔符,我决定遵循
var separators = [' ', '+', '-', '(', ')', '*', '/', ':', '?'];
var tokens = x.split(new RegExp(separators.join('|'), 'g'));?????????????????
But I'm getting error
但我收到错误
Uncaught SyntaxError: Invalid regular expression: / |+|-|(|)|*|/|:|?/: Nothing to repeat
How to solve it?
如何解决?
回答by melc
escape needed for regex related characters +,-,(,),*,?
正则表达式相关字符 +,-,(,),*,?
var x = "adfds+fsdf-sdf";
var separators = [' ', '\\+', '-', '\\(', '\\)', '\*', '/', ':', '\\?'];
console.log(separators.join('|'));
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);
回答by anubhava
This should work:
这应该有效:
var separators = [' ', '+', '(', ')', '*', '\/', ':', '?', '-'];
var tokens = x.split(new RegExp('[' + separators.join('') + ']', 'g'));?????????????????
Generated regex will be using regex character class: /[ +()*\/:?-]/g
生成的正则表达式将使用正则表达式字符类:/[ +()*\/:?-]/g
This way you don't need to escape anything.
这样你就不需要逃避任何事情。
回答by samjudson
The following would be an easier way of accomplishing the same thing.
以下将是完成同一件事的更简单的方法。
var tokens = x.split(new RegExp('[-+()*/:? ]', 'g'));?????????????????
Note that -
must come first (or be escaped), otherwise it will think it is the range
operator (e.g. a-z
)
注意-
必须先来(或被转义),否则会认为是range
操作符(例如a-z
)
回答by Friso
I think you would need to escape the +, * and ?, since they've got special meaning in most regex languages
我认为您需要转义 +、* 和 ?,因为它们在大多数正则表达式语言中具有特殊含义
回答by Roy Dictus
This is because characters like +
and *
have special meaning in Regex.
这是因为字符 like+
和*
在 Regex 中具有特殊含义。
Change your join from |
to |\
and you should be fine, escaping the literals.
将您的连接从|
to更改为|\
您应该没问题,转义文字。
回答by Emanuel
If you want to split based in multiple regexes and dont want to write a big regex
You could use replace
and split
.
Like this:
如果您想基于多个正则表达式进行拆分并且不想编写大的正则表达式,您可以使用replace
和split
。像这样:
const spliters = [
/(\[products\])/g,
/(\[link\])/g,
/(\[llinks\])/g,
];
let newString = "aa [products] bb [link] [products] cc [llinks] dd";
spliters.forEach(regex => {
newString = newString.replace(regex, match => `???${match}???`);
});
const mySplit = newString.split(/???([^?]+)???/)
console.log(mySplit);
This works very well for my case.
这对我的情况非常有效。