简体   繁体   中英

Extract variables from formatted string

I'm trying to see if there's something that exists to do the following. I'd hate to reinvent the wheel.

I have a string like this. It's a file name.

2014-12-22-thomas-javascript.md

I want to be able to provide a format for this schema.

{year}-{month}-{day}-{name}-{topic}.{extension}

And I'd like an object in return.

{
    "year": "2014",
    "month": "12",
    "day": "22",
    "name": "thomas",
    "topic": "javascript",
    "extension": "md"
}

This way of providing a string and a format is very reticent of these two functions from node core util, moment parse, and jekyll post names.

At the risk of reinventing a wheel;

String.parse = function parse() {
    if(typeof arguments[0] === 'string' && typeof arguments[1] === 'string' ) {
        var str = arguments[0];
        var val = arguments[1];
        var array = [], obj = {};

        var re = /(?:{)([a-z]*)(?:})/gi;
        var match, sre = str;
        while(match = re.exec(str)) {
            array.push(match[1]);
            sre = sre.replace(match[0], '(\\w*)');          
        }

        re = new RegExp(sre);
        var matches = val.match(re);
        if(matches) {
            for(var i = 1; i < matches.length; i++) {
                obj[array[i-1]] = matches[i];       
            }
        }
        return obj;
    }
}

No doubt there are a bunch of ways this will break but works with your example;

String.parse("{year}-{month}-{day}-{name}-{topic}.{extension}", "2014-12-22-thomas-javascript.md");

EDIT

And for performing the reverse;

String.format = function format() {
    if (typeof arguments[0] === 'string') {
        var s = arguments[0];

        var re = /(?:{)(\d*)(?:})/gi;
        var a, i, match, search = s;
        while (match = re.exec(search)) {
            for (i = 1; i < arguments.length; i++) {
                a = parseInt(match[1]) + 1;
                s = s.replace(match[0], typeof arguments[a] !== 'object' ? arguments[a] || '' : '');
            }
        }

        re = /(?:{)([a-z]*)(?:})/gi;
        match, search = s;
        while (match = re.exec(search)) {
            for (i = 1; i < arguments.length; i++) {
                if (arguments[i].hasOwnProperty(match[1])) {
                    s = s.replace(match[0], arguments[i][match[1]]);
                }
            }
        }
        return s;
    }
}

Which can accept named object members or positional for non-objects.

String.format("{0}-{name}{1}-{year}-{src}", 20, "abc", { name: "xyz", year: 2014 }, { src: 'StackOverflow' });

20-xyzabc-2014-StackOverflow

I found the code in Hexo, it's like jekyll but built with node.

var Permalink = require('hexo-util').Permalink;
var permalink = new Permalink(':year-:month-:day-:name-:topic.:extension
', {
    segments: {
        year: /(\d{4})/,
        month: /(\d{2})/,
        day: /(\d{2})/
    }
});

permalink.parse('2014-12-22-thomas-javascript.md');
// {year: 2014, month: 12, day: 22, ...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM