0

I am running some JavaScript code in Firefox that doesn't seem to be following the rules of regular expressions. I am trying to split up a String of coordinates, which has some funky whitespace in it, like so:

-117.2967917,35.5189858 -117.2966678,35.5189526

-117.296678,35.5187657 -117.2968027,35.5187999

-117.2967917,35.5189858 

I know that the regex \s is supposed to match all spacing, so I used \s+ to split my string in RegexPal, which worked great, as you can see below:

But for some reason when I run my JavaScript code with this regex, I get a one-element array with the entire String in it. This is my code:

var coordArray = polygonString.split("\s+");

I've tried several different regular expressions, but the split function in my JavaScript doesn't seem to be behaving like it should. It does not yield the same results at RegexPal. Why is this? What am I missing?

Sirko
  • 72,589
  • 19
  • 149
  • 183
Steph
  • 2,135
  • 6
  • 31
  • 44

2 Answers2

5

Use:

var coordArray = polygonString.split(/\s+/);
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Oversight on my part. I hope that's not what earned me a downvote. – John Conde Apr 20 '12 at 19:27
  • Awesome, that worked. I didn't realize I needed to not use quotes. I still don't quite understand why mine doesn't work. – Steph Apr 20 '12 at 19:33
  • @stackoverflow - It doesn't work. It just gives me an array of one element still. – Steph Apr 20 '12 at 19:46
  • @Steph, it didn't work because you tried to split by a string, no a regular expression. Javascript does not implicitly convert between the two. – Paul Draper Apr 04 '14 at 15:59
1

See here, you need to surround the regex with slashes, try polygonString.split(/\s+/);

Community
  • 1
  • 1
blackbourna
  • 1,223
  • 2
  • 16
  • 29
  • I think you have misunderstood how regexes work in JavaScript. *Either* use slashes *or* quotes to delimit a regex for the `split()` operation (but if you use a string, you need to escape your backslashes correctly). – Tim Pietzcker Apr 20 '12 at 19:18