Regular Expressions In javascript
var name = "Richard"; var str = "Once upon a time, Richard conquered Europe." var regex = new RegExp(name, "g"); str = str.replace(regex, "Sir " + name + ", the great, ");
var email = new RegExp("\w*@\w*\.\w*");
var is_valid = email.test("vascy@hotmail.com");
var Characters = new Array();
Characters[0] = new Object();
Characters[0].name = "Timmy";
Characters[0].hp = 40;
Characters[0].maxhp = 50;
Characters[1] = new Object();
Characters[1].name = "Jimmy";
Characters[1].hp = 45;
Characters[1].maxhp = 55;
var str = "[0.name] rocks because he has [0.hp] out of [0.maxhp] but [1.name] is better with [1.hp] out of [1.maxhp]";
var regex = /\[([0-9]+).([^\[\]]+)\]/;
while (info = regex.exec(str)) {
var index = info[1];
var prop = info[2];
str = str.replace(regex, Characters[index][prop]);
}
function StringToObject(str) {
var tokens = str.split(";");
var object = new Object();
for (var i = 0; i < tokens.length; i++) {
var property = tokens[i].substring(0, tokens[i].indexOf("="));
var value = tokens[i].substring(tokens[i].indexOf("=") + 1, tokens[i].length);
object[property] = value;
}
return object;
}
function ObjectToString(object) {
var str = "";
for (var property in object) {
str += property + "=" + object[property] + ";";
}
return str;
}
var reg = new RegExp("[.*]", "g");
var str = "[hello]blah[/hey]";
str.replace(reg);
The important bit here is: var reg = new RegExp("[.*]", "g");| What The Regular Expression Does In Words | perl | javascript |
| Replace the "old" with the "new" throughout a string | $str =~ s/old/new/g | str = str.replace(/old/, "new") |
| Find the position of the first number within a string | $pos = $str =~ m/[0-9]/ | pos = str.search(/[0-9]/); |
| Swap any occurance of "jim" and "bob" anywhere within a string | $str =~ s/(jim|bob)(.*?)(jim|bob)/$3$2$1/ | str = str.replace(/(jim|bob)(.*?)(jim|bob)/, "$3$2$1") |