How to split a string into an array in Javascript?

Asked

Viewed 13,619 times

6

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

var x = "FAT* FAT32*";

And result in something like this:

x[0] = "FAT*";
x[1] = "FAT32*";

3 answers

12


8

You can use the method split as already mentioned, along 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, corresponding alphanumeric characters and asterisk.

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

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

0

You can use the split()

console.log(x.split(" "))
//resultado deverá ser ["FAT*", "FAT32*"]

also the slice()

 var z = x.slice(0,4)
 var y = x.slice(4)
 var d = []
 d.push(z)
 d.push(y)
 console.log(d)
 //resultado deverá ser ["FAT*", "FAT32*"]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.