Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have these two strings...

var str1 = "this is (1) test";
var str2 = "this is (2) test";

And want to write a RegEx to extract what is INSIDE the parentheses as in "1" and "2" to produce a string like below.

var str3 = "12";

right now I have this regex which is returning the parentheses too...

var re = (/((.*?))/g);

var str1 = str1.match(/((.*?))/g);
var str2 = str2.match(/((.*?))/g);

var str3 = str1+str2; //produces "(1)(2)"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
237 views
Welcome To Ask or Share your Answers For Others

1 Answer

Like this

Javascript

var str1 = "this is (1) test",
    str2 = "this is (2) test",
    str3 = str1.match(/((.*?))/)[1] + str2.match(/((.*?))/)[1];

alert(str3);

On jsfiddle

See MDN RegExp

(x) Matches x and remembers the match. These are called capturing parentheses.

For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements 1, ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...