How to split a string into array in JavaScript?

4

There is an elegant way to split a string into an array based on the example:

var x = "FAT* FAT32*";

And that would result in something like this:

x[0] = "FAT*";
x[1] = "FAT32*";
    
asked by anonymous 22.01.2015 / 14:24

2 answers

8

Yes, there is, using split .

var x = "FAT* FAT32*";
var array = x.split(" ");

meuLog(array[0]);
meuLog(array[1]);

function meuLog(msg) {
  div = document.body;
  div.innerHTML = div.innerHTML + '<p>' + msg + '</p>';
}
    
22.01.2015 / 14:33
5

You can use the method split as already mentioned, together with the expression \s+ , which will correspond to one or more spaces.

var str = "FAT* FAT32*";
var match = str.split(/\s+/);

alert(match[0]);
alert(match[1]);

An alternative is to get these values through the regular expression /([\w\*]+)/g , which will correspond to alphanumeric characters and an asterisk.

var str = "FAT* FAT32*";
var match = str.match(/([\w\*]+)/g);

alert(match[0]);
alert(match[1]); 
    
22.01.2015 / 17:54