I am a registered user
I am a registered user

Reputation: 519

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!

Upvotes: 4

Views: 93

Answers (4)

M J
M J

Reputation: 81

Use JavaScript's split() method to split a string into array of substrings. Its Syntax is

myString.split(separator, limit);

where separator is Optional and Specifies the character, or the regular expression, to use for splitting the string. If omitted, then an array with only one item is returned. and limit(optional) is an integer that specifies the number of splits, items after the split limit will not be included in the array.

In your case use

regVar = regVar.split(" ");

It will give you the desired output i.e ["Right", "Left", "Right"];

Upvotes: 2

Turn RegVar into array

Try This

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

now regVar is an array of values

regVar = ['Right','Left','Right'];

Upvotes: 2

ajndl
ajndl

Reputation: 394

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.

Upvotes: 5

tymeJV
tymeJV

Reputation: 104775

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"];

Upvotes: 7

Related Questions