3

I was trying to split this string through "##" delimitter.

var historycookie = "8.4707417,77.0463719:Sector 14:Gurgaon##28.3952729,77.3238274:Sector 15:Faridabad";
var history = historycookie.split("##");
alert(history.length);alert(history[0])

The history.length alert is giving me result as 6. But ideally it should be 2. The history[0] alert is giving undefined. Please help me with this as I am not able to get why this is happening.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Uday Khatry
  • 449
  • 1
  • 8
  • 23
  • 1
    Your code works for me on [JSFiddle](https://jsfiddle.net/fg8n36wq/). It alerts me with 2 then with the text before the `##`. – Angelos Chalaris Jun 14 '16 at 16:50
  • 1
    Even your snippet is working for me -- **EDIT** : When you click on `Run Snippet` several times, the first value increments – tektiv Jun 14 '16 at 16:51
  • Yes, is there any way i can make sure that the js/jquery split function is called? – Uday Khatry Jun 14 '16 at 16:52
  • What kind of server are you using? In some cases (like Coldfusion) # is a special character and could be causing odd behaviors as a result. – nurdyguy Jun 14 '16 at 16:52
  • Related: [Using the variable “name” doesn't work with a JS object](http://stackoverflow.com/q/10523701/4642212). – Sebastian Simon Jun 14 '16 at 17:00
  • Use `console.log` instead of `alert` and use the debugging tools built-in in your browser. That way you can immediately see whether you’ve got the expected result and what the result is exactly otherwise. And paste your JS code in [JSHint](http://jshint.com/) to see related mistakes immediately. – Sebastian Simon Jun 14 '16 at 17:15
  • Possible duplicate of [JSON in javascript array is causing error Cannot read property](http://stackoverflow.com/questions/24877236/json-in-javascript-array-is-causing-error-cannot-read-property). Found by searching “code:"var history" is:q”. – Sebastian Simon Jun 14 '16 at 17:24

1 Answers1

10

"History" (or even "history") is a defined by the browser and representing your history.

history.length; // is returning size of entries in your history
history[0]; // undefined, because it is not an array

Just change the name of the history variable.

Eytibi
  • 545
  • 6
  • 12