0

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.

3
  • 1
    You need to escape [ and ] Commented Jan 11, 2018 at 9:09
  • Where is the string derived from? Commented Jan 11, 2018 at 9:10
  • @guest271314 I've edited the main post. Commented Jan 11, 2018 at 9:13

2 Answers 2

3

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");

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.