Piotr
Piotr

Reputation: 29

Javascript regex on input name

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?

Upvotes: 0

Views: 1302

Answers (2)

Rahil Wazir
Rahil Wazir

Reputation: 10132

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

Upvotes: 2

Lloyd
Lloyd

Reputation: 29668

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].

Upvotes: 1

Related Questions