1

I have got:

var myclass = 'moreElements showAddElements-570';
var re = new RegExp('showAddElements\-\d*');
var m = re.exec(myclass);

alert(m[0]);
alert(m[1]);

First alert results in 'showAddElements-', second alert in 'undefined'. I would like to get '570', what I am doing wrong here? If I test it, I get there at least 'showAddElements-570' ... what am I doing wrong here?

Thx for any tipps!

P.s.: I'd like the number only after 'showAddElements-', all other numbers should be omitted..

4 Answers 4

5

Simply use the correct regex:

var re = /showAddElements-(\d+)/;

I removed the backslash before the dash (not needed) and added parens around the digits to turn it into a capturing group -- otherwise m[1] would always be undefined.

See it in action.

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

2 Comments

Thx, works like a charm! ... D'Oh, I didn't realize there shouldn't be any single (or double) quotes!
@sl3dg3: In JavaScript you can construct regexes either with new Regex("blah") or with the bare /blah/. Different syntax, same result.
3

You need to actually capture the subpattern you want:

/showAddElements-(\d*)/

Note that you don't need to escape - because it has no meaning outside a character class.

Comments

1

Here's some code that works:

var myclass = 'moreElements showAddElements-570';
var re = new RegExp(/showAddElements\-(\d*)/);
var m = re.exec(myclass);
alert(m[1]);

There were two problems with the RegExp line. First problem is that the expression was wrapped with single quotes instead of slashes. This blew my mind the first time I realized what was up, had no clue you could wrap something with slashes. Without these it was just treated as a string intend of an expression.

The second problem is that the there were no () around the number part. You need that to actually "grab" that part.

Here's a working link: http://jsfiddle.net/MvG2C/

Comments

0

You have to add parentheses around the desired class in order to capture it:

var re = new RegExp('showAddElements\-([0-9]*)');

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.