I want to pull the tokens out of this string and build an array (this is a simplified example):
SELECT * FROM {token1} WHERE {token2}
So I have an array of two elements:
myArray[0] = "token1"
myArray[1] = "token2"
Is there a clever way to do this without iterating through the string?
I also don't want duplicates in the array, so
The quick {token1} dog {token2} over the {token1} wall
Will give;
myArray[0] = "token1"
myArray[1] = "token2"
(The real reason for this, is for using dates in the SQL statements.)
Mick
You can use replace to have a regex loop run on the string and pull the tokens:
var sql = 'SELECT * FROM {token1} WHERE {token2}';
var tokens = [];
sql.replace(/\{(.*?)}/g, function(a, b) {
tokens.push(b);
});
console.log(tokens);
You can try this regex :
(?:{)([^}]*)(?:})
Example code:
var str = 'SELECT * FROM {token1} WHERE {token2}';
var regex = new RegExp('(?:{)([^}]*)(?:})', 'g');
var match, myArray = [];
while (match = regex.exec(str)) myArray.push(match[1]);
console.log(myArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With