James
James

Reputation: 4052

Javascript RegEx contains

I'm using Javascript RegEx to compare if a string matches a standart format.

I have this variable called inputName, which has the following format (sample):

input[name='data[product][tool_team]']

And what I want to achieve with Javascript's regex is to determine if the string has the following but contains _team in between those brackets.

I tried the following:

var inputName = "input[name='data[product][tool_team]']";
var teamPattern = /\input[name='data[product][[_team]]']/g;
var matches = inputName.match(teamPattern);
console.log(matches);

I just get null with the result I gave as an example. To be honest, RegEx isn't really my area, so I suppose it's wrong.

Upvotes: 0

Views: 86

Answers (2)

guest271314
guest271314

Reputation: 1

If you are trying to check for DOM elements you can use attribute contains or attribute equals selector

document.querySelectorAll("input[name*='[_team]']")

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074999

A couple of things:

  1. You need to escape [ and ] as they have special meaning in regex

  2. You need .* (or perhaps [^[]*) in front of _team if you want to allow anything there ([^[]* means "anything but a [ repeated zero or more times)

Example if you just want to know if it matches:

var string = "input[name='data[product][tool_team]']";

var teamPattern = /input\[name='data\[product\]\[[^[]*_team\]'\]/;
console.log(teamPattern.test(string));

Example if you need to capture the xyz_team bit:

var string = "input[name='data[product][tool_team]']";

var teamPattern = /input\[name='data\[product\]\[([^[]*_team)\]'\]/;
var match = string.match(teamPattern);
console.log(match ? match[1] : "no match");

Upvotes: 3

Related Questions