Created
March 24, 2014 22:57
-
-
Save bennadel/9751128 to your computer and use it in GitHub Desktop.
Using Methods in Javascript Replace Method
This file contains 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
// Turns the vowel characters into random cases. | |
String.prototype.RandomCase = function(){ | |
return( | |
this.replace( | |
new RegExp("([aeiou]{1})", "gi"), | |
// Here, we are passing in a nameless function as the parameter for | |
// the "replace" argument of the String Replace method. It uses the $1 | |
// to refer to the grouping of vowels found in the regular expression. | |
function($1){ | |
// Get a random number. | |
if (Math.random() > .5){ | |
// Lowercase this one. | |
return( $1.toLowerCase() ); | |
} else { | |
// Uppercase this one. | |
return( $1.toUpperCase() ); | |
} | |
} | |
) | |
); | |
} | |
// Create a test string with plenty of vowels. | |
var strTest = "Ben Nadel is a Pretty Nice Guy. I really like Kinky Solutions and his Coding Style."; | |
// Alert the random-cased string. | |
alert( strTest.RandomCase() ); |
This file contains 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
String.prototype.GetSmallWords = function(){ | |
// Declare the array that will hold the small words matches. | |
var arrWords = new Array(); | |
// Take the string value and get copy the small words into an array. | |
this.replace( | |
new RegExp("(a|and|be|do|for|go|he|hi|i|in|is|no|of|on|the|to)", "gi"), | |
// This replace function takes the word found and adds the | |
// word to the locally-defined array of short words in the | |
// parent function. | |
function( strWord ){ | |
arrWords[ arrWords.length ] = strWord; | |
} | |
); | |
// Return the array of little words. | |
return( arrWords ); | |
} | |
// Create a test string with small words. | |
var strTest = "Ben Nadel is a Pretty Nice Guy. I really like Kinky Solutions and his Coding Style."; | |
// Alert the array of small words. | |
alert( strTest.GetSmallWords() ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment