nickforall
nickforall

Reputation: 614

Get words from a string pattern in Javascript

I am trying to get words from a string dynamically using a pattern. The pattern and input look something like this

var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";

Now I want to be able to have an array of the variables like this

["nick", "javascript"]

Upvotes: 0

Views: 724

Answers (2)

John
John

Reputation: 770

var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
var outputArr = [];

pattern.split(" ").forEach(function (e, i){
  e === "%var%" ? outputArr.push(input.split(" ")[i]) : "";
});

outputArr is the desired array.

Upvotes: 0

jabclab
jabclab

Reputation: 15042

This should do it:

var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";

var re = new RegExp(pattern.replace(/%var%/g, '([a-z]+)'));
var matches = re.exec(input).slice(1); // <-- ["nick", "javascript"]

The variable re is a RegExp whose pattern is the pattern variable with each instance of %var% replaced with a capturing group of lower case letters (extend if necessary).

matches is then the result of the re regex executed on the input string with the first element removed (which will be the full matching string).

Upvotes: 2

Related Questions