Javascript Regexp Usage
by queryj
JavaScript
// regexp exec
var matches = /hello \S+(\w{4,}#)/.exec('This is a hello world! hello world#');
var el = document.createElement('span');
var el2 = document.createElement('span');
var el3 = document.createElement('div');
el.innerHTML = matches[0];
el2.innerHTML = matches[1];
el3.innerHTML = matches[2];
document.body.appendChild(el);
document.body.appendChild(el2);
document.body.appendChild(el3);
// regexp match
var str = "For mor e information, see Chapter 3.4..5.1";
var re = /(chapter \d+([\.\d])*)/i;
var found = str.match(re);
console.log("found len:", found.length);
console.log(found);
console.log('***********');
re = /chapter (\d+)(\.\d)*/i;
found = str.match(re);
console.log("found len:", found.length);
console.log(found);
// regexp replace
function replacer(match, p1, p2, p3, offset, string){
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
console.log("match=", match);
return [p1, p2, p3].join(' - ');
};
newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log("newString=", newString);
var num = "12,345";
var i = parseNumber(num);
console.log("converted int is ", i);