4

I have a regex which splits a string into an array at every space and keeps the space value in each occurrence as follows:

var str = "[This is a test]";
var foo = str.toLowerCase().split(/(\S+\s+)/).filter(function(n) {return n});

This returns the following on all modern browsers:

["[This ", "is ", "a ", "test]"];

But on IE8 all I get is ["test]"];

It seems that IE8 doesn't read the \S regex character correctly. Does anyone know of a workaround for IE8 to reproduce the correct array?

Thanks

kapa
  • 77,694
  • 21
  • 158
  • 175
  • `\s` does not include non-breaking whitespace but it seems IE uses one. non-breaking whitespace is: `\xa0`. So you pattern becomes: `([^\s\xa0]+[\s\xa0]+)` – Leri Feb 27 '14 at 10:01
  • try [this](http://stackoverflow.com/questions/7935153/regex-match-works-in-ff-chrome-but-not-ie-8) str.replace(/\u00a0/g, ' ') – winterfall Feb 27 '14 at 10:02
  • Could anybody explain why this works in Chrome? :) `split` should remove the separator, should it not? – kapa Feb 27 '14 at 10:23
  • 1
    [I see now](http://devdocs.io/javascript/global_objects/string/split#Example:_Capturing_parentheses), `If separator contains capturing parentheses, matched results are returned in the array.` This seems to be the feature that does not work in IE8. – kapa Feb 27 '14 at 10:25

1 Answers1

4

I do not see why you're complicating things using split() and a callback. Just match instead of splitting !

/\S+\s*/g

  • \S+ : match any non-whitespace character one or more times.
  • \s* : match any whitespace character zero or more times.
  • g     : a modifier to match all.

Note: IE8 doesn't support Array.filter().

Online demo

kapa
  • 77,694
  • 21
  • 158
  • 175
HamZa
  • 14,671
  • 11
  • 54
  • 75