4

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!

4 Answers 4

7

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"];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I should have thought of that before!
5

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.

1 Comment

I didn't know about the bonus!
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'];

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.