0

I have inputs with names:

<input type="text" name="data[Site][search]">
<input type="text" name="data[Site][name]">

I want to get when I click only:

search
name
etc.

My JS in click event

var reg = /data\[Site\]\[\d\]/g;
var test = $(this).attr("name").match(reg);
console.log(test);

But console display null. What is wrong in my reg?

0

2 Answers 2

2

Try with using this:

var reg = /data\[Site\]\[(.+)\]/g;          //Capture the characters between []
var test = reg.exec($(this).attr("name"));
console.log(test[1]);                       //Output search | name

Demo

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

Comments

1

You're using \d which means digits only, you're also not specifying a quantifier so you'll only capture one digit at most, i.e:

data[Search][1]

You could use \S which is any non-whitespace character. You want to do this for at least one character (as you shouldn't have data[Search][] and you'll also want to capture the name, so throw in some (). You could switch \S to specific characters using character sets, for example [A-Za-z0-9].

Anyhow, your modified example should not look something like this:

var reg = /data\[Site\]\[(\S+)\]/g;
var test = $(this).attr("name").match(reg);

console.log(test);

You'll be able to pull the actual value from the match captures using test[1].

2 Comments

Thank you, I have a question. how can I display only this string? Now in console have: ["data[Site][search]"] I want only search
Try console.log(test[1])

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.