I’m doing some form of data visualization learning for 180 days because I need to #JFDI.

See post explaining how and why I’m doing this.

*Reading for these last precious few days before taking off for Christmas – where I’ll finish the Udacity course

Code Learning:

Learn JS Data Regular Expressions

  • Replacing with Regular Expressions
    • Example of replacing “wood” with the word “nun.”
var str = “how much wood would a woodchuck chuck if a woodchuck could chuck wood”;
var regex = /wood/g;
var newstr = str.replace(regex), “nun”

console.log(newstr);

=> “How much nun would a nunchuck chuck if a nunchuck could chuck nun”

Finding Numbers

  • Extracting money from groceries as an example.  You’d need to define a regular expression that defines a patterns, for example in the below
  • Dollar sign as (\$) to indicate beginning of a price
  • Set of repeating characters than can be 0-9 or period(.) We denote these care appear repeatedly (+).
  • Word break to indicate end of the price string (\b)
var message = “I bought a loaf of bread for $3.99, some milk for $2.49 and” + “a box of chocolate cookies for $6.95”;
regex = /\$([0-9\.]+)\b/g;
matches = message.match(regex)console.log(matches);

=>  [“$3.99”, “$2.49”, “$6.95”]
  • Since we can’t add with $ signs, reduce!
matches.reduce(function(sum, value) {
return sum + Number(value.slice(1));
}, 0);

=>13.43
  • Using special characters
    • \d – any number character, equivalent to [0-9]
    • \D – any nonnumber character, equivalent to [^0-9]
    • \s – any single space character.  This includes a single space, tab, line feed or form feed.

 

 

Posted in , , ,

Leave a Reply