相当于 PhP preg_split 的 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6824327/
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
JavaScript equivalent of PhP preg_split
提问by Randomblue
Is there an equivalent of the PhP function preg_splitfor JavaScript?
是否有与JavaScript的 PhP 函数preg_split等效的函数?
回答by Mark Elliot
Any string in javascript can be split using the string.split
function, e.g.
javascript 中的任何字符串都可以使用该string.split
函数进行拆分,例如
"foo:bar".split(/:/)
where split
takes as an argument eithera regular expression or a literal string.
其中split
取作为参数或者一个正则表达式或文字串。
回答by Tarik
You can use regular expressions with split.
您可以将正则表达式与 split 一起使用。
The problem is the escape characters in the string as the (? opens a non capturing group but there is no corresponding } to close the non capturing group it identifies the string to look for as '
问题是字符串中的转义字符 (? 打开了一个非捕获组,但没有相应的 } 来关闭非捕获组,它将要查找的字符串标识为 '
回答by Brett Zamir
If you want support for all of the preg_split arguments see https://github.com/kvz/phpjs/blob/master/_workbench/pcre/preg_split.js(though not sure how well tested it is).
如果您想支持所有 preg_split 参数,请参阅https://github.com/kvz/phpjs/blob/master/_workbench/pcre/preg_split.js(虽然不确定它的测试情况如何)。
Just bear in mind that JavaScript's regex syntax is somewhat different from PHP's (mostly less expressive). We would like to integrate XRegExpat some point as that makes up for some of the missing features of PHP regexes (as well as fixes the many browser reliability problems with functions like String.split()).
请记住,JavaScript 的正则表达式语法与 PHP 的有些不同(主要是表达性较差)。我们希望在某个时候集成XRegExp,因为它弥补了 PHP 正则表达式的一些缺失功能(以及修复了许多浏览器可靠性问题,例如 String.split())。