問題描述
是否有任何標准說明“aba”.split(/a/) 是否應該返回 1,2 或 3 個元素? (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?
‑‑‑‑‑
參考解法
方法 1:
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.
(by qbolec、Denys Séguret)