1

Is it somehow possible to convert a string to an array as easy as possible without any hacks? and without splitting the string at some point?

For example bringing this:

temp = 'Text';

to this:

temp = ['Text'];

It might be a simple question but I couldn't find any solution without splitting the string.

4
  • 6
    temp = [temp]; ? It is not really clear what you are asking... Commented Jan 22, 2021 at 17:47
  • Weeell yeah that's the solution. Didn't thought about that, sorry. Commented Jan 22, 2021 at 17:50
  • Why not just create an array and add your string to it???? Commented Jan 22, 2021 at 17:53
  • Do you want the string split? [ "T", "e", "x", "t" ]? Commented Jan 22, 2021 at 17:54

2 Answers 2

4

const temp = 'text';

console.log(new Array(temp));
console.log([temp]);
console.log(temp.split());
console.log([].concat(temp));

There are a few options out there.

Sign up to request clarification or add additional context in comments.

Comments

3

If you want an array with the string as a single value just create a new array with that string.

temp = [temp]; 

Comments

Your Answer

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