Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Fun with .match
var fs = require('fs');
var assert = require("assert");
// Example 1 ----------------------------------------- //
var myDomain = "www.nhunzaker.com/this_article";
assert( myDomain.match("nhunzaker.com") );
// Example 2 ----------------------------------------- //
var myString = "Hello, world! My name is Nate Hunzaker!";
var name = myString.match(/My name is (.*) (.*)!/);
assert.equal(name[1], "Nate");
assert.equal(name[2], "Hunzaker");
// Example 3 ----------------------------------------- //
var story = fs.readFileSync("wotw.txt").toString();
var pattern = "(.*)\\:(.*)\n";
var lines = story.match(new RegExp(pattern, "g") );
var data = {};
lines.forEach(function(line) {
var match = line.match( new RegExp(pattern) );
if (match) {
var key = match[1].toLowerCase();
var value = match[2].trim();
data[key] = value;
}
});
assert.equal(data.title, "The War of the Worlds");
assert.equal(data.author, "H.G. Wells");
assert.equal(data.body.substring(0, 12), "No one would");
console.log("Good to go!");
TITLE: The War of the Worlds
AUTHOR: H.G. Wells
BODY: No one would have believed in the last years of the nineteenth century that this world was being watched keenly and closely by intelligences...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment