Burkhard
Burkhard

Reputation: 14738

Function is only executed halfway

I have this function in JS:

function test(value, requirement)
{
    console.log("value: '" + value + "' requirement: '" + requirement + "'");
    var regExp = new RegExp(requirement, '');
    console.log("regExp: " + regExp);
    var str = "" + value;
    console.log("str: " + str);// [1]
    var ok = str.test(regExp);// [2]
    console.log("ok: " + ok); // [3]
    return ok;
}

I execute it in Firefox with Firebug enabled and the console shows:

value: '123' requirement: '^123$'
regExp: /^123$/
str: 123

Until 1 everything works as expected. Why is [3] not executed? What's the problem with [2] and how do I fix it?

Edit: I used the code from here (sorry, it's german) and no errors in the console.

Upvotes: 0

Views: 78

Answers (3)

user786
user786

Reputation: 4364

Syntax error

It should be

  regExp.test(str)

test is a method of regEx. type string does not have any method named "test"

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281785

test() is a method of the RegExp, not the string - you need this:

var ok = regExp.test(str); // [2]

(Also, you should always run your code with the JavaScript console open - that would show you an error message that would help you identify the problem.)

Upvotes: 1

elclanrs
elclanrs

Reputation: 94131

test is a method of RegExp, not String:

regExp.test(str)

Upvotes: 1

Related Questions