1

Okay, I am making a text based game and I have been using the switch command like so

switch(true){
case /run/.test(g1):
    prompt("run");
    break;
}

the question I have is can I can I change the name of the test() method like so

switch(true){
case /run/.act(g1):
    prompt("run");
    break;
}

I thought if I created a function like so it would work

function act(str){
test(str);
return;
}

but it didn't... any help would be nice.

edit: fixed switch statements

K4b6
  • 35
  • 6
  • 2
    What are you trying to do? `/something/` is a regex object and the same as `new RegExp('/something/')`. Do you want to add your own prototype to the regex object? **Why?** – h2ooooooo Nov 26 '13 at 18:48
  • 2
    Is using `switch` like that actually valid? Should be `switch (value)` AFAIK... – Jacob Nov 26 '13 at 18:49
  • oh sorry I should have stated that I have the var "g1" calling a text-box on the web page to get the string. then the switch statement is wondering if /something/ is in the string if so it carries on I just want to rename the .test(g1) at the end so it looks like .act(g1) just because every time i read it I feel like I'm calling a test function I made earlier – K4b6 Nov 26 '13 at 18:53

2 Answers2

1

So /run/ is a regex object. It has a method called test. It doesn't have a method act, so hence you can't call act() on it.

You'll need to use prototypes:

switch{
     case /run/.act(g1):
     prompt("run");
     break;
}
RegExp.prototype.act = function (str) {
    return this.test(str);
}

Here's an explanation of Prototypes.

Community
  • 1
  • 1
Niall Paterson
  • 3,580
  • 3
  • 29
  • 37
0

If you really need to do this (please see What is the XY problem?) then you can add a prototype to the RegExp object.

var regex = /fo+/;
var str = 'fooooooooooooooo';

regex.test(str); //true

RegExp.prototype.act = function(str) {
    if (str == 'fooooooo' && this.test(str)) {
        return true;
    } else {
        return false;
    }
}

regex.act(str); //false (str is not 'fooooooo')

Likewise, you can make an alias (but please, don't - it works fine as it is) by simply returning this.test():

RegExp.prototype.act = function(str) {
    return this.test(str);
}
Community
  • 1
  • 1
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102