javascript - How to get the content in parentheses using regular expressions in js?
滿天的星座
滿天的星座 2017-05-19 10:40:53
0
6
716

var str="deleteChild(236737)";
For example, get the number in parentheses 236737 Others are not required.
How to write regular js.
js array is too troublesome. Because the number in the parentheses will change.

滿天的星座
滿天的星座

reply all(6)
某草草

Use d+ to indicate any whole number. In order to match the content at a special location, the concept of group in regular expressions is also used (shown in regular expressions as being enclosed by a pair of parentheses).

The shortcut way of expressing JavaScript regular expression is to enclose it with "/", for example /正则表达式内容/, it has an exec method, and the incoming parameter is the string to be checked.
The execution result of the exec method returns an array or null value (when there is no content in str that matches the regular expression).

If the regular expression contains group and the content is matched, then in the returned result array, the text content represented by group will appear in the second array element and subsequent array elements of the result array (when the regular expression contains When containing multiple groups).

var str = "deleteChild(236737)";
var result = /\((\d+)\)/.exec(str);

if(result.length > 1) {  //加这个判断是以防字符串中没有匹配的内容,那么result[1]会抛错!
   console.log("您想要的结果是:" +result[1]); //输出 236737。 
} else {
   console.log("字符串中没有符合条件的数字");
}
淡淡烟草味
var number = "deleteChild(236737)".replace(/.*\((\d+)\)$/, '$1');
大家讲道理

You can use the split method of string. split() 方法用于把一个字符串分割成字符串数组。

var num1=str.split("(")  //["deleteChild", "236737)"]
var num2=num1[1].split(")") //["236737", ""]
var result=num[0]
Peter_Zhu

My answer is also based on the principle of high-voted answers, but I personally think it may be easier to understand if I write it this way

var str = "deleteChild(236737)";
var reg= /\((\d+)\)/;

if(reg.test(str)){ //如果匹配上直接获取括号里的内容
    console.log(RegExp.) //236737
}
仅有的幸福
/\d+/g
左手右手慢动作

I agree with the writing method on the 4th floor, it is so simple and convenient.
Systematic learning of regular expressions, I highly recommend the regular expression front-end user manual | louis blog
sf link: Regular expression front-end user manual-Louis chats about the front-end-SegmentFault
The original content is super long , a very comprehensive summary.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template