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!
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"];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With