Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

javascript - Get string inside parentheses, removing parentheses, with regex

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...