如何使用Regex提取onChange方法的String参数?

时间:2022-09-13 11:15:15

I have select elements as below

我有如下选择元素

<select name="selectid1" id="selectid1" onChange="script.selectChange(this,'tr');">.......</select>

and

<select name="selectid2" id="selectid2" onChange="script.selectChange(this,'div');">.......</select>

I want to extract the selectChange method's String paramter (the 2nd paramter) tr and div of the onChange attribute of both the select elemets using regular expresssion.

我想使用常规表达式提取selectChange方法的String参数(第二参数)tr和两个选择元素的onChange属性的div。

I can get the value of onChange using

我可以使用onChange获取值

var selectid1 = $('#selectid1').attr('onChange'); //script.selectChange(this,'tr');

and

var selectid2 = $('#selectid2').attr('onChange'); //script.selectChange(this,'div');

What regex should I use in order to get strings 'tr' and 'div' from the variables?

为了从变量中获取字符串'tr'和'div',我应该使用什么正则表达式?

2 个解决方案

#1


1  

If it's just for test case - use the following approach with String.match function:

如果它仅用于测试用例 - 请使用以下方法使用String.match函数:

var selectid1 = "script.selectChange(this,'tr')",
    param = selectid1.match(/,\s?['"]([^)]+)['"]/)[1];

console.log(param);  // tr

#2


1  

/onChange="script.selectChange\(this,'([^']*)'/g

Demo here --> https://regex101.com/r/uW2aQ6/1

在这里演示 - > https://regex101.com/r/uW2aQ6/1

#1


1  

If it's just for test case - use the following approach with String.match function:

如果它仅用于测试用例 - 请使用以下方法使用String.match函数:

var selectid1 = "script.selectChange(this,'tr')",
    param = selectid1.match(/,\s?['"]([^)]+)['"]/)[1];

console.log(param);  // tr

#2


1  

/onChange="script.selectChange\(this,'([^']*)'/g

Demo here --> https://regex101.com/r/uW2aQ6/1

在这里演示 - > https://regex101.com/r/uW2aQ6/1