0

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"]
nickforall
  • 556
  • 6
  • 7
  • 3
    What if `pattern` is "hello this is %var% using %var%" and `input` is "hello this is nick using nick using javascript"? – afuous Mar 20 '16 at 21:10
  • It's used in a function that checks if it matches with the pattern first, so that won't happen. @voidpigeon – nickforall Mar 20 '16 at 22:17
  • Possible duplicate of [How do you access the matched groups in a JavaScript regular expression?](http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression) – Andy Hoffner Mar 20 '16 at 22:32

2 Answers2

2

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).

jabclab
  • 14,786
  • 5
  • 54
  • 51
0

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.

John
  • 760
  • 5
  • 12
  • 3
    Please don't ever use `for(var i in patternArr)` to iterate an array. That is a bad practice because the iteration will also include any enumerable properties of the array object, not only array elements. Use `.forEach()`, a traditional `for (var i = 0; i < patternArr.length; i++)` loop or in ES6, you can use `for (let item of patternArr)`. – jfriend00 Mar 20 '16 at 21:26
  • I'd suggest you modify your answer to fix it. You use the "edit" link under your answer. – jfriend00 Mar 20 '16 at 21:44
  • @jfriend00 how do i get the index, when i use "let item of patternArr"? – John Mar 20 '16 at 21:52
  • That version doesn't given you the index. It gives you the actual array item which you can just directly use without having to fetch it out of the array. If you need the index for other reasons, then it is not the best option. I'd suggest you just use `.forEach()`which gives you both the item and the index. – jfriend00 Mar 20 '16 at 21:54