15

Is there an equivalent of the PHP function preg_split for JavaScript?

Avatar
  • 14,622
  • 9
  • 119
  • 198
Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • 2
    possible duplicate of [javascript equivalent of php's preg_replace](http://stackoverflow.com/questions/407256/javascript-equivalent-of-phps-preg-replace) – Lightness Races in Orbit Jul 26 '11 at 01:38
  • or a duplicate of this http://stackoverflow.com/questions/4437919/split-a-string-using-javascript – qw3n Jul 26 '11 at 01:40

3 Answers3

37

Any string in javascript can be split using the string.split function, e.g.

"foo:bar".split(/:/)

where split takes as an argument either a regular expression or a literal string.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
0

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).

Just bear in mind that JavaScript's regex syntax is somewhat different from PHP's (mostly less expressive). We would like to integrate XRegExp at 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()).

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
0

You can use regular expressions with 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 '

Tarik
  • 79,711
  • 83
  • 236
  • 349
  • Meta commentary: this answer is currently terminated at `for as '`. However when I go to edit it I see the whole thing in the preview... huh. Not sure what to do - in the unlikely case a migration or upgrade chewed something somewhere, fixing the comment might mask a bug. – i336_ Aug 21 '21 at 16:56