Search code examples
javascriptnode.jsstring-formatting

How to "reverse format"


I am trying to find a way to capture data from string inputs, and put them in easy to work with containers. For instance:

var message = "Sarah has been promoted to Superintendent";

I know how to test for the string against a regex and return whether or not it matches:

message.test(\[a-zA-Z]+ has been promoted to [a-zA-Z]+\g);

However I'm stumped at figuring out how, then, to find the indices of the regex matches to place them in an object:

Promotion { name: "Sarah" , position: "Superintendent" }

I feel like the answer is on the tip of my brain cells but I'm at a loss. What are the steps to capture, say, the index of the first wildcard in the string, separate that word, and then do that for the next piece of data (being flexible enough to handle up to 9 or so "wildcard pieces"?


Solution

  • Check out String.prototype.match: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

        let message = "Sarah has been promoted to Superintendent";
        let [, name, position] = message.match(/([a-zA-Z]+) has been promoted to ([a-zA-Z]+)/);
        let promotion = {name, position};
        
        console.log(promotion);