Regular Expressions – Samples

Posted: June 24, 2010 in Regular Expressions
Tags:

string.match – matches a string and a RE – use g flag for all occurrences
var m = “this is my text is this”.match(“is”); // m.length returns only 1
m = “this is my text is this”.match(/(is)/g); // m.length returns 4 – whole word match
m = “this is my text is this”.match(/[is]/g); // m.length returns 8 – individual char match
m = ‘<html><head><title>hi</title></head><body>bye</body></html>’.match(/(<[a-zA-Z]+>)|(<\/[a-zA-Z]+>)/g); // m.length returns 8 – matches all html tags        
               
string.replace –  use g flag for all occurrences
var p = ‘(555)666-1212’.replace(/\((\d{3})\)/g,’$1-‘); //555-666-1212
// $ has special meaning when it is part of the replaceValue Ex: $1, $$, $&, $`, $’
p = ‘(555)666-1212′.replace(/\((\d{3})\)/g,’$$’); //$-666-1212
p = ‘(555)666-1212′.replace(/\((\d{2})\)/g,’$&’); //(555)666-1212 – replaces with the same matched text
p = ‘1(555)666-1212′.replace(/\((\d{3})\)/g,’$`’); // 11666-1212  – replaces with preceding text of the matched text
p = ‘(555)666-1212’.replace(/\((\d{3})\)/g,”$'”); //666-1212666-1212 – replaces with following text of the matched text

Function.prototype.method = function (name, func) {
    if(!this.prototype[name])
        this.prototype[name] = func;
    //return this;
};
String.method(‘entityfy’, function() {
    var chars = {‘<‘:’&lt;’, ‘<‘:’&gt;’, ‘&’:’&amp;’, ‘”‘:’&quot;’};
    return function() {return this.replace(/[<>&]/g, function(c) {return chars[c];});};
});

string.search
var text = “search in this text”;
var pos = text.search(/(h)/); // pos = 4

string.split
var words = text.split(/( )/); // words.length – 7, spaces also exist in array
var words2 = text.split(” “); // words2.length – 4, spaces not exist in array

//Other interesting string functions

//string.toLocaleUpperCase() // locale specific
//string.toLocaleLowerCase() // locale specific
//string.charCodeAt() // returns 67 for C
var a = String.fromCharCode(67, 97, 116); // a = Cat

regexp.exec – powerful and slowest methods of RE. If it successfully matches then it returns an array with 0th element matched substring, 1st element text captured by group1, 2nd element text captured by group2

var re = /(<[a-zA-Z]+>)|(<\/[a-zA-Z]+>)/g;
var result = re.exec(“<html><head><title>hi</title></head><body>bye</body></html>”); // result.length – 3 – does not match all occurances
var a;
while((a = re.exec(“<html><head><title>hi</title></head><body>bye</body></html>”))) {
    // a.length – gives 3 for 8 times due to 8 matched tags
}

regexp.test – simplest and fastest method of RE
var b = re.test(“<html><head><title>hi</title></head><body>bye</body></html>”); // b is true

Leave a comment