Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable to array?

I have a variable that looks like this: var regVar="Right Left Right;" And then I split them: regVar.split(); So what I am trying to do is to make the variable called regVar to be turned into an array. I thought that there was an .array() method, but I couldn't figure out how it works. If there is a jQuery method, that would be fantastic as well as plain JS. Thanks for you help in advance!

like image 560
I am a registered user Avatar asked Dec 05 '22 05:12

I am a registered user


2 Answers

You have to specify what you're splitting on and re-assign to a variable, I assume it's the space in the string, so:

var regVar="Right Left Right;"
var arrayOfRegVar = regVar.split(" ");

console.log(arrayOfRegVar); //["Right", "Left", "Right"];
like image 176
tymeJV Avatar answered Dec 09 '22 13:12

tymeJV


To split a string by spaces, use .split(" ");

You split a string by anything just by passing delimiter (ie. separator) as an argument to split().

Examples:
"hello world".split(' ') returns ["hello", "world"]
"google.com".split('.') returns ["google", "com"]
"415-283-8927".split('-') returns ["415", "283", "8927"]

Bonus:
If you use an empty string as the delimiter, the string is split by the character:
"helloworld".split('') returns ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] (an element in the array for every character including space)

However, if you use nothing (.split()), an array containing that unchanged string will be returned.

like image 20
ajndl Avatar answered Dec 09 '22 15:12

ajndl