Reputation: 198
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?
Upvotes: 1
Views: 486
Reputation: 570
Try this
const str = "arg1,arg2,arg3";
const [arg1,arg2,arg3] = str.split(',');
console.log(arg1,arg2,arg3);
Upvotes: 0
Reputation: 1610
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]}`);
}
Upvotes: 0
Reputation: 50291
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)
Upvotes: 0
Reputation: 370789
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
Upvotes: 10