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"]
3
  • 3
    What if pattern is "hello this is %var% using %var%" and input is "hello this is nick using nick using javascript"? Commented Mar 20, 2016 at 21:10
  • It's used in a function that checks if it matches with the pattern first, so that won't happen. @voidpigeon Commented Mar 20, 2016 at 22:17
  • Possible duplicate of How do you access the matched groups in a JavaScript regular expression? Commented Mar 20, 2016 at 22:32

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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).
I'd suggest you modify your answer to fix it. You use the "edit" link under your answer.
@jfriend00 how do i get the index, when i use "let item of patternArr"?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.