Created
October 28, 2012 18:04
-
-
Save nhunzaker/3969319 to your computer and use it in GitHub Desktop.
Fun with .match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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