Jack Thor
Jack Thor

Reputation: 1594

RegEx match not working

So what I want to match is anything that ends with ".ProjectName" so I wrote a small test case. I purposely created the pattern using RegExp because in the real case scenario I will be using a variable as part of the reg ex pattern. I'm not sure if my pattern is not correct (90% sure it correct), or if I am misusing the match function (70% sure I am suing it right). The blow code returns me something when the second case notMatchName should not return me anything

var inputName = "ProjectName";
var matchName = "userInput_Heading.Heading.ProjectName";
var notMatchName = "userInput_Heading.Heading.Date";
var reg = new RegExp(".*[." + inputName + "]");
console.log(reg);
console.log(matchName.match(reg));
console.log(matchName.match(reg)[0]);
console.log(notMatchName.match(reg));
console.log(notMatchName.match(reg)[0]);

Here is the JsFiddle to help.

Upvotes: 0

Views: 97

Answers (2)

amdorra
amdorra

Reputation: 1556

your regular expression should be .*\.projectName

if you rewrite your statement it will be

var reg = new RegExp(".*\." + inputName)

Upvotes: 1

FrankPl
FrankPl

Reputation: 13315

Use

var reg = new RegExp(".*\." + inputName);

The square brackets mean: one character, which is one of those within the brackets. But you want several characzters, first a dot, then the first character of inputName, etc.

Upvotes: 2

Related Questions