Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript extract tokens from string [closed]

Tags:

javascript

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

like image 737
Mick Avatar asked Jun 19 '26 02:06

Mick


2 Answers

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);
like image 120
KevBot Avatar answered Jun 21 '26 15:06

KevBot


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);
like image 32
MaxZoom Avatar answered Jun 21 '26 16:06

MaxZoom