Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript(regex): excluding matches from output

I have this text: nisi non text600 elit where 600 is added dynamically. How can I get it?

var str = ('nisi non text600 elit').match(/text\d+/);
alert(str);

This alerts text600, how can I alert only 600 without an additional replace of the word text(if that is possible)?

Any help is appreciated, thank you!

like image 528
user557108 Avatar asked May 22 '12 11:05

user557108


People also ask

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

How do you exclude words in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

What is \d in JavaScript regex?

The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9].

Does empty regex match everything?

An empty regular expression matches everything.


2 Answers

var str = ('nisi non text600 elit').match(/text(\d+)/);
alert(str[1]);
like image 173
antyrat Avatar answered Oct 05 '22 14:10

antyrat


Use parentheses to catch a group in the regular expression:

var str = ('nisi non text600 elit').match(/text(\d+)/)[1];

Note: A regular expression literal is not a string, so you shouldn't have apostrophes around it.

like image 28
Guffa Avatar answered Oct 05 '22 13:10

Guffa