1

Is there a way to split a string which is comma separated in to a new string? Simular to substring() method and the split() method.

So I want to separated this by the commas in the string:

let str = "arg1,arg2,arg3"; //and so on

and then put each value into a new string like this:

let str1 = "arg1";
let str2 = "arg2";
let str3 = "arg3";

Is there a way to do that in JavaScript?

Hazmatron
  • 181
  • 2
  • 16
  • 1
    Why not just use an array instead of using individual variables? – Eddie Jun 05 '18 at 04:16
  • 2
    Creating variables dynamically is not a good idea. Just use `.split` and work with the array it returns. [Convert comma separated string to array](https://stackoverflow.com/q/2858121/218196) – Felix Kling Jun 05 '18 at 04:16
  • Also related: [“Variable” variables in Javascript?](https://stackoverflow.com/q/5187530/218196) – Felix Kling Jun 05 '18 at 06:46

4 Answers4

10

One way to do this concisely is to use destructuring on the split string:

const str = "arg1,arg2,arg3";
const [str1, str2, str3] = str.split(',');
console.log(str1);
console.log(str2);
console.log(str3);

But it would usually be more appropriate to use an array instead

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • thanks for the help, and also very quickly how would you do this depend on the length of the string from a user input? if you get what I mean. – Hazmatron Jun 05 '18 at 04:49
  • @HarrySmart If the number of items in the array isn't certain, I would definitely assign the result of the `split` to an actual array instead of destructuring into separate variable names. – CertainPerformance Jun 05 '18 at 04:50
  • @CertainPerformance I see. well thank you very much for your help. – Hazmatron Jun 05 '18 at 05:09
0

Split the string using .split and then use destructuring assignment which will unpack the values from array

let [str1, str2, str3] = "arg1,arg2,arg3".split(",");
console.log(str1)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can make a dynamic object if this str is dynamic,

let str = "arg1,arg2,arg3";
let strArr = str.split(',');
let strObj = {};

strArr.forEach((item, index) => {
   strObj['str'+ index] = item;
});

for(let str in strObj) {
  console.log(`${str} : ${strObj[str]}`);
}
Senal
  • 1,510
  • 1
  • 14
  • 22
0

Try this

const str = "arg1,arg2,arg3";

const [arg1,arg2,arg3] = str.split(',');

console.log(arg1,arg2,arg3);
Gilbert lucas
  • 519
  • 7
  • 22