Question

filename = "file_1";
name = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);

Expected Result:

file
1

Actual Result:

f
i

http://jsfiddle.net/j667q/1/

I must be doing something wrong, but can't for the life of me work out what.

I have tried:

  • Using different quotes ' and "
  • Defining filename and name before using (filename = ''; name = [];)
  • Spliting using a different character ('-')
Was it helpful?

Solution 2

The problem is, something to do with global conflicts the global object has a property called name and is somehow conflicting with your code.

rename it http://jsfiddle.net/j667q/3/

you could do var name = ...split... if you don't want to rename it

Yeah, also note, you should ALWAYS declare variables with var there is no reason not to, if you want a global property do window.someName = something;

OTHER TIPS

Define the array variable first:

var name = [];

DEMO http://jsfiddle.net/j667q/5/

Why this works?

Update for more clarification based on comments:

Although name is not a reserved word, it's a global property of window (eg. window.name and name mean the same), var name; will define a new variable called name which is in another scope and avoids the conflict.

JavaScript Reserved words: http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

Declare the variables as var to scope them properly

var filename = "file_1";
var names = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);

name is a js global property. so try not to use it. hope that will help

you have to declare both variables like this.

var filename = "file_1";
var name = filename.split('_');

check out the updated JSFIDDLE (http://jsfiddle.net/prakashcbe/j667q/17/)

Try this... Other answers all are correct. I don't know your mistake. Anyway, try this as well

[http://jsfiddle.net/puvanarajan/Nytgh/][1]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top