Reputation: 1516
This is my string:
('Vegetable', 'startswith', 'k', true)
I want split this like below
i have tried like below but cant get my solution
Upvotes: 1
Views: 75
Reputation: 15247
You can first get rid of the first opening parenthesis and the last closing one using replace()
The pattern /^\((.*?)\)$/
gets an opening parenthesis at the begining, then capture everything up to (but not including) the last closing parenthesis.
Now that the string is epured, "('Vegetable', 'startswith', 'k', true)"
becoming "'Vegetable', 'startswith', 'k', true"
, you can use a traditional split()
:
console.log("('Vegetable', 'startswith', 'k', true)".replace(/^\((.*?)\)$/, "$1").split(', '));
If you want to convert the parts of the result that contains "true"
or "false"
as boolean value, you can map()
the result :
console.log("('Vegetable', 'startswith', 'k', true, false)".replace(/^\((.*?)\)$/, "$1")
.split(', ')
.map(elem => elem === "true" ?
true :
elem === "false" ?
false :
elem));
Upvotes: 1