The question is simple. I have a string that contains multiple elements which are embedded in single-quotation marks:
var str = "'alice' 'anna marie' 'benjamin' 'christin' 'david' 'muhammad ali'"
And I want to parse it so that I have all those names in an array:
result = [
'alice',
'anna marie',
'benjamin',
'christin',
'david',
'muhammad ali'
]
Currently I’m using this code to do the job:
var result = str.match(/\s*'(.*?)'\s*'(.*?)'\s*'(.*?)'\s*'(.*?)'/);
But this regular expression is too long and it’s not flexible, so if I have more elements in the str string, I have to edit the regular expression.
What is the fastest and most efficient way to do this parsing? Performance and felxibility is important in our web application.
I have looked at the following question but they are not my answer:
Define the pattern once and use the global
gflag.If you want the tokens without the single quotes around them, the normal approach would be to use sub-matches in REGEX – however JavaScript doesn’t support the capturing of sub-groups when the
gflag is used. The simplest (though not necessarily most efficient) way around this would be to remove them afterwards, iteratively:[EDIT] – as the other answers say, you could use
split()instead, but only if you can rely on there always being a space (or some common delimiter) between each token in your string.