2

I am trying to split a string by three keywords like so:

var option=$(this).text().split(/(To:|From:|Line:)/);

$(this).text() is for testing purposes "From:Circular Quay To:Manly Line:F1 Manly"

All "normal" browsers return an array of 7 elements but IE7 & 8 returns an array of 3 elements.

Any ideas?

11
  • 1
    Well what happens in IE7/8? Commented Jul 15, 2013 at 6:18
  • it spits out an array of three undefined values... Commented Jul 15, 2013 at 6:20
  • What's the text you try to split ? Is it the same for all browsers ? Commented Jul 15, 2013 at 6:21
  • do you try console.log($(this).text());? Commented Jul 15, 2013 at 6:21
  • 2
    In ID 7/8 it is giving "["Circular Quay ","Manly ","F1 Manly"]" Commented Jul 15, 2013 at 6:41

1 Answer 1

3

regex spliting doesn't work the same in all browsers, as is described by this article.

  • Internet Explorer excludes almost all empty values from the resulting array (e.g., when two delimiters appear next to each other in the data, or when a delimiter appears at the start or end of the data). This doesn't make any sense to me, since IE does include empty values when using a string as the delimiter.

  • Internet Explorer and Safari do not splice the values of capturing parentheses into the returned array (this functionality can be useful with simple parsers, etc.)

  • Firefox does not splice undefined values into the returned array as the result of non-participating capturing groups.

  • Internet Explorer, Firefox, and Safari have various additional edge-case bugs where they do not follow the split specification (which is actually quite complex).

(note : those behaviors changed somewhat in recent browsers, don't rely on these descriptions for implementing browser specific algorithms!)

The good news for you, if the order of delimiters is always the same : What probably really interests you, that is the content strings, will be here in all browsers. So you just have to test each string of the array to see if it's an empty string or a delimiter.

If your string always has the delimiters in the same order, you might want to strip them in all browsers by not capturing them :

var s = s.split(/To:|From:|Line:/);

If you need the delimiters because their order may change, then you'd better split on \b and check all strings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.