Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any standard which says if "aba".split(/a/) should return 1,2, or 3 elements?

From what I've tested

"aba".split(/a/).length

returns

  • 1 in ie8
  • 3 in firefox, chrome, opera

I was always prepared to handle differences in DOM manipulation, or Events model, but I've thought that things like strings, regexps, etc. are well defined. Was I wrong?

like image 869
qbolec Avatar asked Nov 23 '12 07:11

qbolec


1 Answers

IE removes from the split result array all undefined or empty strings.

As your question seems to be about the existence of a standard, then EcmaScript is the best match in the Javascript world.

And the behavior of split on regex is documented : http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.14

As it obvious from the example, empty strings should not be removed from the resulting array, so IE (as suspected) is faulty.

"A<B>bold</B>and<CODE>coded</CODE>".split(/<(\/)?([^<>]+)>/)

    evaluates to the array

["A", undefined, "B", "bold", "/", "B", "and", undefined,  "CODE", "coded", "/", "CODE", ""]

In fact, there are other differences between browsers. A solution could be to use a cross-browser split regex script but it's probably better to be simply aware of the differences and handle with proper tests the array returned by split. Or use some tricks.

like image 122
Denys Séguret Avatar answered Oct 20 '22 21:10

Denys Séguret